轉自: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
打開這個文件,因為Qt5的qapplication在QtWidgets模塊里,和Qt4不一樣,Qt4的qapplication在QtGui模塊里,因此需要加上如下配置項:
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
然后執行
qmake hello.pro
可以看到已經生成了Makefile文件
接下來就是根據Makefile文件構建應用程序了,執行程序:
mingw32-make 【此時編譯器mingw32會自動在當前目錄下查找Makefile文件並根據Makefile文件內容編譯鏈接相應的文件】
如果沒有報錯,說明編譯成功了!
進入release目錄下可以看到兩個文件:hello.exe helloworld.o
直接運行hello.exe就可以看到效果了,一個可愛的200x100大小的巨型按鈕窗口出現了。
問題解決:
問題一:‘qmake’不是內部或外部命令,也不是可運行的程序或批處理文件。
這個問題很好解決,主要是因為環境變量沒有配置好。Win+R輸入SystemPropertiesAdvanced:
在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
這個錯誤主要是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