QT應用 7 多執行緒 QT4 7以後的版本

2021-10-16 03:37:16 字數 1596 閱讀 3924

與前篇4.7以前版本一塊看會更有啟發。

demo示例

過程如下圖所示:

注意事項:1.建構函式不能指定父物件pmyt_ =new mythread;不能寫成pmyt_ =new mythread(this)

2.子執行緒不處理ui視窗        不能有qmessagebox之類。只處理資料相關的操作。

//1.自定義執行緒pmyt_ =new mythread;

//2.系統執行緒 pt_=new qthread(this);

//3.關聯兩個 pmyt_->movetothread(pt_);

//4.啟動系統執行緒pt_->start()

//5.自定義執行緒 訊號->槽函式工作

//6.關閉執行緒pt_->quit() pt_->wait()

mythread.h

#ifndef mythread_h

#define mythread_h

#include #include #include//1.派生於qobject

//2.執行緒處理函式為自定義domywork(),不再是run()

class mythread : public qobject

;#endif // mythread_h

mythread.cpp

#include "mythread.h"

//不可以有ui相關的類

mythread::mythread(qobject *parent) : qobject(parent)

void mythread::domywork()

mainwindow::~mainwindow()

void mainwindow::init()

ptimer_->start(500);

if(pt_->isrunning()==true)

if(pt_->isrunning())

// 啟動執行緒 但沒有啟動執行緒處理函式

pt_->start();

pmyt_->setflag(false);

//觸發訊號才讓子執行緒工作函式開始工作

emit singalworking();

} void mainwindow::slotstop()

pmyt_->setflag(true);

pt_->quit();

pt_->wait();

} //關閉執行緒

void mainwindow::slotclosethread()

pmyt_->setflag(true);

pt_->quit();

pt_->wait();

} //定時器

void mainwindow::slottimeout()

Qt 4 7開發環境的搭建

依然是在ubuntu10.04下。另外注意現在已不是qtopia時代,現在的qt一次編寫,到處執行,下圖中qt libraries 4.7.2 for linux x11和qt libraries 4.7.2 for embedded linux兩個包的內容是完全一樣的。以root身份執行安裝是因為...

Qt4 7中 預設的建構函式

初學qt,發現每個例子自帶的建構函式 network.h標頭檔案 include netserverthread.h class network public qobject network.cpp include netserverthread.h network network qobject ...

QT 多執行緒應用

qt多執行緒的實現有兩種方法,一種是繼承qthread的多執行緒使用方法,另外一種是使用qobject實現多線的方法。傳統的方式是繼承qtread,但是這種方式比較的容易出錯,qt官方推薦使用的是第二種方式。這裡介紹這兩種方式的最簡單的一種建立方式。threadone.h ifndef thread...