独立线程中实现QT GUI

在网上搜集的资料:

http://www.qtcentre.org/threads/16552-Starting-QT-GUI-in-a-seperate-Thread
http://*.com/questions/16812602/qt-main-gui-and-other-thread-events-loops
http://*.com/questions/9777911/how-do-i-create-a-window-in-different-qt-threads
http://*.com/questions/16501284/qt-updating-main-window-with-second-thread

据这些资料看,在非主线程中处理QT或多或少都会有些问题,但我在文档里倒是没有明确找到说QApplication一定要定义在主线程中。

所以下面尝试了一下:

独立线程中实现QT GUI
 1 #include <windows.h>
 2 #include <process.h>    /* _beginthread, _endthread */
 3 #include <stdlib.h>
 4 #include <QtGui/QApplication>
 5 #include <QtGui/QPushButton>
 6 
 7 void initUI(void* dummy) {
 8     int argc = 0;
 9     QApplication app(argc, NULL);
10     QPushButton button("Hello, world");
11     button.show();
12     app.exec();
13     printf("gui thread dead.\n");
14     _endthread();
15 }
16 
17 int main(int argc, char** argv)
18 {
19     /* Launch gui thread. */
20     _beginthread( initUI, 0, NULL );
21 
22     /* Do something with main thread */
23     while(1){
24         printf("tick ...\n");
25         
26         Sleep(1000);
27     }
28 }
独立线程中实现QT GUI

运行结果来看似乎并没有多少问题:

独立线程中实现QT GUI

后续再看。

----------------附:PYQT编译步骤----------------

1. 下载QT library for windows并安装(C:/QT/4.8.5),并将C:/QT/4.8.5/bin目录添加到系统环境变量中(后续编译依赖qt的qmake):
http://download.qt-project.org/official_releases/qt/4.8/4.8.5/qt-win-opensource-4.8.5-vs2010.exe

2. 下载PYQT source package并解压(C:/PyQt-win-gpl-4.10.3)
http://sourceforge.net/projects/pyqt/files/PyQt4/PyQt-4.10.3/PyQt-win-gpl-4.10.3.zip

3. 下载SIP source package并解压(C:/sip-4.15.4)
http://sourceforge.net/projects/pyqt/files/sip/sip-4.15.4/sip-4.15.4.zip

4. 在VS2010的命令提示行环境下执行(编译sip并安装pyd至python目录):

1 cd c:/sip-4.15.4
2 python configure.py
3 nmake
4 nmake install

5. 在VS2010的命令提示行环境下执行(编译pyqt):

1 cd c:/pyqt-win-gpl-4.10.3
2 python configure-np.py
3 nmake
4 nmake install

6. 在python解释器中测试:

>>> import sipconfig         #测试sip
>>> from PyQt4.QT import *   #测试pyqt

独立线程中实现QT GUI

上一篇:OCP新题,2019题库出现大量新题,062-第22题


下一篇:Fireworks教程:立体质感水晶的制作过程