1. 程式人生 > 其它 >QT程式新建一個執行緒

QT程式新建一個執行緒

1、建立好一個QT應用程式

2、手動建立新執行緒類,繼承QThread

  我這裡新建的是下面 newthread.h 和 newthread.cpp 檔案。

  newthread.h

#ifndef NEWTHREAD_H
#define NEWTHREAD_H

#include <QThread>

class NewThread : public QThread  //這裡畫底色部分要自己新增
{
public:
    NewThread();
    void run();  //重構QThread類的run函式
};

#endif // NEWTHREAD_H

  newthread.cpp

#include "newthread.h"
#include <QDebug>

NewThread::NewThread()  //新建檔案時自己生成的函式
{
}

void NewThread::run() //這個函式執行你要執行的程式碼
{
    while(true)   
    {
        qDebug()<<"test thread";
        sleep(2);
    }
}

3、在你的QT應用主執行緒中啟動新執行緒

  下面是我主執行緒的程式碼

#include "avs200_od_proction_test.h"
#include 
"ui_avs200_od_proction_test.h" #include <string.h> #include <QProcess> #include <QDebug> #include <QString> #include "newthread.h"
avs200_od_proction_test::avs200_od_proction_test(QWidget
*parent) : QMainWindow(parent) , ui(new Ui::avs200_od_proction_test) { ui->setupUi(this
); NewThread *myThread = new NewThread(); //建立新執行緒物件,執行該句時會執行 newthread.cpp 中的 NewThread::NewThread() 函式 myThread->start(); //啟動執行緒, 停止執行緒是 myThread->stop() 在你需要停止的地方呼叫即可; } avs200_od_proction_test::~avs200_od_proction_test() { delete ui; }