1. 程式人生 > >qt 中建立一個工作執行緒(例子)

qt 中建立一個工作執行緒(例子)

當一個事件需要很長的處理時間,就建立一個工作執行緒,防止主介面卡死。

1.新建一個QT的gui專案,裡面包含main.cpp,mainwindow.h,mainwindow.cpp,mainwindow.ui檔案

2.新建一個頭檔案thread.h,派生一個執行緒類,重新寫一個執行緒的入口函式。

#ifndef THREAD_H
#define THREAD_H
class MyThread:public QThread
{
    Q_OBJECT
public:
    MyThread(QObject *parent);

void run();//執行緒入口函式(工作執行緒的主函式)
} #endif // THREAD_H

3.新建thread.cpp,定義run()函式

#include"thread.h"
#include<sstream>
#include<iostream>
using namespace std;
MyThread::MyThread(QObject *parent)
    :QThread(parent)
{
}
MyThread::~MyThread()
{

}void MyThread::run()
{
    cout<<"開始執行執行緒"<<endl;
    QThread::msleep(
10000); cout<<"執行緒執行完畢"<<endl; }

4.在mainwindow.h中匯入thread.h檔案,並宣告執行緒

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include"thread.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0
); ~MainWindow(); private: Ui::MainWindow *ui; MyThread *task;//宣告執行緒 }; #endif // MAINWINDOW_H

4.在mainwindow.cpp檔案的建構函式中例項化執行緒並啟動執行緒。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "thread.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    task=new MyThread(NULL);
    task->start();
}

MainWindow::~MainWindow()
{
    delete ui;
}

結果: