转自:http://www.cnblogs.com/csulennon/p/4479236.html

在上一篇随笔中已经搭建好了Qt5的的开发环境,并且通过Qt Creator自动构建了一个视窗程序。在这篇文章中我们将手动编写一个HelloWold程序,简单了解一下Qt的构建过程。这里我们不会涉及到Qt代码部分,因此可以先不用理会代码是怎么回事,复制粘贴就行。

首先编写helloworld.cpp

复制代码
#include <QPushButton>
#include <QApplication>

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

    QPushButton btn("hello world");
    btn.resize(200,100);
    btn.show();
    return app.exec();
}
复制代码


我将其放在D:\Workspace\qt\hello,你可以放在任何你喜欢的目录下,但最好不要包含中文目录.

然后win+r 输入cmd回车,进入控制台,进入到源代码目录下

qmake –project

这时候会生成一个“目录名.pro”的文件,我这里生成的是hello.pro

image

打开这个文件,因为Qt5的qapplication在QtWidgets模块里,和Qt4不一样,Qt4的qapplication在QtGui模块里,因此需要加上如下配置项:

QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

image

然后执行

qmake hello.pro

可以看到已经生成了Makefile文件

image

接下来就是根据Makefile文件构建应用程序了,执行程序:

mingw32-make   【此时编译器mingw32会自动在当前目录下查找Makefile文件并根据Makefile文件内容编译链接相应的文件】    

image

如果没有报错,说明编译成功了!

进入release目录下可以看到两个文件:hello.exe  helloworld.o

image

直接运行hello.exe就可以看到效果了,一个可爱的200x100大小的巨型按钮窗口出现了。

image

 

问题解决:

问题一:‘qmake’不是内部或外部命令,也不是可运行的程序或批处理文件。

这个问题很好解决,主要是因为环境变量没有配置好。Win+R输入SystemPropertiesAdvanced

image

image

在path后面追加两条数据,并以英文分号“;”分隔。分别是

(1)D:\Qt\Qt5.4.0\5.4\mingw491_32\bin; 这个目录是我Qt的安装目录,需要根据自己的安装情况设置,设置这个目录主要是为了使用qmake命令,也就是说你需要配置的目录就是qmake.exe所在的目录路径。

(2)第二个是mingw32-make.exe的路径,我的是在D:\Qt\Qt5.4.0\Tools\mingw491_32\bin;两个目录配置好之后,从新打开cmd窗口就会生效了。

问题二:mingw32-make执行错误

复制代码
D:\Workspace\qt\hello>mingw32-make
mingw32-make -f Makefile.Release
mingw32-make[1]: Entering directory 'D:/Workspace/qt/hello'
g++ -c -pipe -fno-keep-inline-dllexport -O2 -frtti -Wall -Wextra -fexceptions -mthreads -DUNICODE -DQT_NO_DEBUG -DQT_GUI
_LIB -DQT_CORE_LIB -DQT_NEEDS_QMAIN -I. -I'.' -I'../../../Qt/Qt5.4.0/5.4/mingw491_32/include' -I'../../../Qt/Qt5.4.0/5.4
/mingw491_32/include/QtGui' -I'../../../Qt/Qt5.4.0/5.4/mingw491_32/include/QtCore' -I'release' -I'../../../Qt/Qt5.4.0/5.
4/mingw491_32/mkspecs/win32-g++' -o release/helloworld.o helloworld.cpp
helloworld.cpp:1:23: fatal error: QPushButton: No such file or directory
 #include <QPushButton>
                       ^
compilation terminated.
Makefile.Release:121: recipe for target 'release/helloworld.o' failed
mingw32-make[1]: *** [release/helloworld.o] Error 1
mingw32-make[1]: Leaving directory 'D:/Workspace/qt/hello'
makefile:34: recipe for target 'release' failed
mingw32-make: *** [release] Error 2
复制代码

image

这个错误主要是Qt的版本引起的,Qt5的QApplication在QtWidgets模块里,Qt4的qapplication在QtGui模块里。

因此需在.pro文件中加入:

QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

这两行即可。

总结:

总的流程其实很简单:

(1)编写源文件

(2)qmake –project

(3)修改*.pro

(4)qmake  *.pro

(5)mingw32-make