[Qt][Qt 多线程][上]详细讲解

时间:2025-02-11 18:31:54
// class MyThread : public QObject { Q_OBJECT public: // ... void Thread(); void SetFlag(bool flag = true); signals: void Notify(); private: bool isStop() = false; }; // void MyThread::Thread() { while(!isStop) { QThread::sleep(1); emit Notofy(); qDebug() << " ⼦线程号: " << QThread::currentThread(); if(isStop) { break; } } } void MyThread::SetFlag(bool flag) { isStop = flag; } ------------------------------------------------------------------------- // class Widget : public QWidget { // ... MyThread* myThread; QThread* thread; signals: void StartSignal(); // 启动子线程信号 private slot: void on_startPushbutton_clicked(); void on_closePushbutton_clicked(); void DelSignals(); void DealClose(); }; // // 构造函数中 { // 动态分配空间,不能指定⽗对象 myThread = new MyThread(); // 创建子线程 thread = new QThread(this); // 将⾃定义的线程加⼊到⼦线程中 myThread->moveToThread(thread); connect(myThread, &MyThread::Notify, this, &Widget::DelSignals); connect(this, &Widget::StartSignal, myThread, &MyThread::Thread); connect(this, &Widget::destroyed, this, &Widget::DealClose); } void MyWidget::on_startPushbutton_clicked() { if(thread->isRunning() == true) { return; } // 启动线程但是没有启动线程处理函数 thread->start(); // 不能直接调⽤线程处理函数,直接调⽤会导致线程处理函数和主线程处于同⼀线程 emit StartSignal(); } void MyWidget::DelSignals() { static int i = 0; i++; ui->lcdNumber->display(i); } void MyWidget::on_closePushbutton_clicked() { if(thread->isRunning() == false) { return; } myThread->SetFlag(); thread->quit(); thread->wait(); } void MyWidget::DealClose() { delete myThread; on_closePushbutton_clicked(); }