天天看點

Qt學習(1)——Qt第一行代碼第一行代碼

第一行代碼

顯示Qt版本

// version.cpp

#include <QtCore>
#include <iostream>

int main() {

    std::cout << "Qt version: " << qVersion() << std::endl;
}
           

qVersion()

函數顯示目前Qt版本。

其中-I後為Qt包含的頭檔案路徑,-L後為Qt的庫檔案路徑,需要根據自己的實際路徑更改。

在Linux系統下運作上述指令,在我的電腦上面的輸出結果如下:

$ ./version 
Qt version: 
           

可以看出來,我安裝的Qt版本為5.10.0.

一個簡單的GUI應用

因為要用到

qmake

建立工程檔案(暫且這麼叫吧),先建立一個名為

simple

的檔案夾:

$ mkdir simple
           
// simple/simple.cpp
#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[]) {

    QApplication app(argc, argv);

    QWidget window;

    window.resize(, );
    window.setWindowTitle("Simple example");
    window.show();

    return app.exec();
}
           

qmake

建構應用

$ qmake -project
           

會生成一個擴充名為

.pro

的檔案,在本示例中,為

simple.pro

.

檢視檔案内容為:

######################################################################
# Automatically generated by qmake (3.1) Tue Feb 6 12:48:45 2018
######################################################################

TEMPLATE = app
TARGET = simple
INCLUDEPATH += .

# The following define makes your compiler warn you if you use any
# feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

# Input
SOURCES += simple.cpp
           

繼續執行

qmake

make

指令,會提示如下錯誤:

g++ -c -pipe -O2 -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -I. -I. -I../../../Qt//gcc_64/include -I../../../Qt//gcc_64/include/QtGui -I../../../Qt//gcc_64/include/QtCore -I. -isystem /usr/include/libdrm -I../../../Qt//gcc_64/mkspecs/linux-g++ -o simple.o simple.cpp
simple.cpp::: fatal error: QApplication: 沒有那個檔案或目錄
 #include <QApplication>
                        ^
compilation terminated.
Makefile:: recipe for target 'simple.o' failed
make: *** [simple.o] Error 1
           

經過和http://zetcode.com/gui/qt5/introduction/的

simple.pro

的比較之後,發現是最後一行缺少

QT += widgets

,加上之後在執行

qmake

make

,就會發現錯誤已經消失了。

然後在運作生成的可執行檔案,就可以看到GUI視窗了

$ ./simple
           
Qt學習(1)——Qt第一行代碼第一行代碼

參考:1.http://zetcode.com

Qt

繼續閱讀