方法1:思路圖:
直接上**:
主函式:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include #include mainwindow::mainwindow(qwidget *parent) :
qmainwindow(parent),
ui(new ui::mainwindow)
void mainwindow::dealdone()
void mainwindow::on_pushbutton_clicked()
//非常複雜資料處理,耗時較長
// qthread::sleep(5);
//處理完資料後,關閉定時器
// timer->stop();
thread.start();
qdebug()<
}void mainwindow::stopthread()
主標頭檔案:
#ifndef mainwindow_h
#define mainwindow_h
#include #include #include "mythread.h"
namespace ui
class mainwindow : public qmainwindow
;#endif // mainwindow_h
執行緒函式標頭檔案:
#ifndef mythread_h
#define mythread_h
#include class mythread:public qthread
;#endif // mythread_h
執行緒函式cpp:
#include "mythread.h"
mythread::mythread(qobject *parent):qthread(parent)
void mythread::run()
方法2:
1、新增乙個執行緒類:mythread
1)、基於乙個類,繼承於qobject
2)、在類中設定乙個執行緒函式(只可設定乙個函式為執行緒函式)
2、在主視窗中
1)建立執行緒物件(不能指定父物件)
例如:mythread myt = new mythread;
2)qthread子執行緒物件
qthread thread = new qthread(this);
3)把自定義執行緒類加入到子執行緒中
myt->movetothread(thread);
(a)啟動子執行緒,只是將執行緒開啟了,並沒有啟動執行緒處理函式
thread.start();
(b)執行緒的啟動,必須通過訊號與槽函式
connect(this,&widget::startthread,myt,&mythread::mytimeout);//啟動執行緒
emit startthread();
**實現如下:
#ifndef mythread_h
#define mythread_h
#include #include class mythread : public qobject
;#endif // mythread_h
#include "mythread.h"
#include mythread::mythread(qobject *parent) : qobject(parent)
void mythread::mytimeout()
class widget : public qwidget
;#endif // widget_h
#include "widget.h"
#include "ui_widget.h"
#include widget::widget(qwidget *parent) :
qwidget(parent),
ui(new ui::widget)
//啟動執行緒,但是沒有啟動執行緒處理函式
thread->start();
myt->setflag(false);
//不能直接呼叫執行緒處理函式
//直接呼叫導致執行緒處理函式和主線程同乙個處理函式
//myt->mytimeout();
//只能通過訊號槽的方法使用
emit startthread();
}void widget::dealsignal()
static int i = 0;
++i;
ui->lcdnumber->display(i);
}void widget::on_pushbutton_2_clicked()
void widget::dealcolse()//關閉視窗時候關閉執行緒
Qt中多執行緒的使用教程
當執行緒的任務量比較大時,頻繁建立和銷毀執行緒會有很大的記憶體開銷,此時使用qthread的方法就不合適,應該使用執行緒池qthreadpool。qthread適用於常駐記憶體的任務,qthreadpool適用於不常駐記憶體,任務量比較大的情況。qrunnable 是乙個非常輕量的抽象類,它的主體是...
QT多執行緒的使用(moveToThread方法)
qt有兩種實現多執行緒的方法,一種是 子類化qthread,然後去重寫run函式,實現多執行緒 一種是 子類化qobject,然後使用movetothread函式實現多執行緒 由於qt官方推薦使用第二種方法,所以我這裡主要介紹一下,如何通過子類化qobject去實現多執行緒。首先,我們寫乙個繼承qo...
QT 多執行緒 使用UI
直接上 qt的ui操作必須在主線程做的,分支執行緒只能傳送訊息給主線程進行引導操作。所以平常我們的 都是直接使用乙個執行緒來調動ui,但是不同的執行緒同時需要使用ui來顯示結果之類的就需要相互協調 如果沒有invoke之類的方法,可以考慮直接使用qt 的qthread 直接使用thread會衝突 1...