第一行代码
显示Qt版本
// version.cpp
#include <QtCore>
#include <iostream>
int main() {
std::cout << "Qt version: " << qVersion() << std::endl;
}
qVersion()函数显示当前Qt版本。
$ g++ -o version version.cpp -I/usr/local/qt5/include/QtCore -I/usr/local/qt5/include -L/usr/local/qt5/lib -lQt5Core -fPIC
其中-I后为Qt包含的头文件路径,-L后为Qt的库文件路径,需要根据自己的实际路径更改。
在Linux系统下运行上述命令,在我的电脑上面的输出结果如下:
$ ./version
Qt version: 5.10.0
可以看出来,我安装的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(250, 150);
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/5.10.0/gcc_64/include -I../../../Qt/5.10.0/gcc_64/include/QtGui -I../../../Qt/5.10.0/gcc_64/include/QtCore -I. -isystem /usr/include/libdrm -I../../../Qt/5.10.0/gcc_64/mkspecs/linux-g++ -o simple.o simple.cpp
simple.cpp:1:24: fatal error: QApplication: 没有那个文件或目录
#include <QApplication>
^
compilation terminated.
Makefile:681: 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

参考:1.http://zetcode.com
本文介绍Qt初学者如何显示Qt版本及构建一个简单的GUI应用程序。通过命令行编译Qt程序,并解决构建过程中的常见问题。
3609

被折叠的 条评论
为什么被折叠?



