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);
}
}