Qt学习(1)——Qt第一行代码

第一行代码

显示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

继续执行qmakemake命令,会提示如下错误:

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,加上之后在执行qmakemake,就会发现错误已经消失了。

然后在运行生成的可执行文件,就可以看到GUI窗口了

$ ./simple

simple example

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值