Qt QThread
阿新 • • 發佈:2018-12-14
QThread類提供了與平臺無關的執行緒。
QThread從run()函式執行。run()通過呼叫exec()來開啟事件迴圈,並在執行緒內執行一個Qt事件迴圈。
要建立一個執行緒,需要子類化QThread,並且重新實現run()函式。
#ifndef MYQTHREAD_H #define MYQTHREAD_H #include <QThread> class myQThread : public QThread { Q_OBJECT public: explicit myQThread(QObject* parent = 0); void stop(); protected: void run(); private: volatile bool stopped; }; #endif // MYQTHREAD_H
#include "myqthread.h" #include <QDebug> myQThread::myQThread(QObject* parent): QThread(parent) { stopped = false; } void myQThread::run() { qreal i = 0; while(!stopped) { qDebug()<<QString("in myQThread:%1").arg(i); msleep(1000); i++; } stopped = false; } void myQThread::stop() { stopped = true; }
void MainWindow::on_startButton_clicked() { if(!thread.isRunning()) { qDebug()<<"thread is not running"; } thread.start(); ui->stopButton->setEnabled(true); ui->startButton->setEnabled(false); } void MainWindow::on_stopButton_clicked() { if(thread.isRunning()) { qDebug()<<"thread is running"; thread.stop(); ui->stopButton->setEnabled(false); ui->startButton->setEnabled(true); } }