
win.h
#ifndef WIN_H #define WIN_H #include <QWidget> #include <thread> #include <chrono> #include <QDebug> class Win : public QWidget { Q_OBJECT public: Win(QWidget *parent = nullptr); ~Win(); private: void hello(); //線程要調用的函數 std::thread* t; //注意:這個變量不要在構造函數中定義成局部變量,否則構造函數結束,線程對象就釋放了 }; #endif // WIN_H
win.cpp
#include "win.h" Win::Win(QWidget *parent) : QWidget(parent) { this->resize(400,300); t=new std::thread(&Win::hello,this); //創建線程並啟動 //t 線程名 //參數1:線程要執行的函數地址 } Win::~Win() { } void Win::hello() { for (int i = 0; i < 30; i++) { qDebug() << "子線程:" << i; std::this_thread::sleep_for(std::chrono::seconds(2)); //本線程休眠2秒 } }
工程下載地址:鏈接:https://pan.baidu.com/s/18CQTU_i8WcJfif1CoUQmRA 提取碼:6666

