UI线程为主线程,比较耗时的计算或操作,比如网络通信中的文件传输,在主线程中操作,用户界面可能会冻结不能及时响应。
多线程应用程序:在上述情况下,可以创建一个单独的工作线程来执行比较消耗时间的操作,并与主线程之间处理好同步与数据交互。
方式一:
QT4.7 之前的版本 : 此版本如果一个线程挂了,退出这个线程,那么线程所对应的函数也退出
1)工作线程自定义一个类,必须继承于QThread,线程处理函数和主线程不在同一个线程
class MyThread:public QThread
void run() // run()虚函数,需要重写
{
sleep(5); // 父类为QThread,所以不用写成 QThread::sleep(5)
emit isDone
}
2) 启动线程,不能直接调用run() ,start()间接调用run()
Mythread *thread thread->start()
部分代码:
1 thread = new mythread(this); //分配空间 2 connect(thread,&mythread::isDone,this,&pthWidget::DealDone); 3 connect(this,&mythread::destroyed,this,&mythread::stopthread); //当按窗口右上角关闭时触发线程关闭函数 4 5 void pthWidget::stopthread() 6 { 7 thread->quit(); //terminate 暴力关闭 容易导致内存问题 8 thread->wait();//等待线程处理完手头工作 9 } 10 void pthWidget::DealDone() 11 { 12 timer->stop(); //处理完数据以后 关闭定时器 13 qDebug()<<"over"; 14 } 15 void pthWidget::on_pushButton_clicked() 16 { 17 if(timer->isActive() == false)//如果定时器没有工作 18 timer->start(100); //100ms 19 // QThread::sleep(50);//非常复杂的数据处理,耗时较长 20 //启动线程处理数据 21 thread->start(); 22 } 23 ///工作线程类 24 #include "mythread.h" 25 mythread::mythread(QObject *parent) : QThread(parent) 26 { 27 } 28 void mythread::run() 29 { 30 sleep(50);//非常复杂的数据处理,耗时较长 31 emit isDone(); 32 }