當一個事件需要很長的處理時間,就創建一個工作線程,防止主界面卡死。
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; }
結果:

