单线程在某些情况下会阻塞进程,这时候就需要另外开辟一个线程来处理这事儿,QThread 就是这个作用。
代码实现
新建一个console程序,然后添加一个类 mythread,基于 QThread。代码是参考 Qt 线程 :http://inching.org/2014/05/03/qt-thread/ 的。
mythread.h
#ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> #include <QtCore> class MyThread : public QThread { Q_OBJECT public: explicit MyThread(QObject *parent = 0); protected: void run(); signals: public slots: }; #endif // MYTHREAD_H
mythread.cpp
#include "mythread.h" MyThread::MyThread(QObject *parent) : QThread(parent) { } void MyThread::run() { for( int count = 0; count != 20; ++count ){ qDebug()<<count; sleep( 1 ); } qDebug()<<"mythread finish!"; }
main.cpp
#include <QCoreApplication> #include "mythread.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyThread thread; thread.start(); //thread.wait(); QThread::sleep( 2 ); qDebug()<<"main thread here"; return a.exec(); }
代码测试
运行后,可以看到是两个线程同时执行的
源码下载
扩展阅读
- 再试 Qt5 使用 QThread
http://davidrobot.com/2015/04/qt5_qthread_2.html