qt多线程继承QThread,是通过重写run()函数来实现。
本文通过在子线程实现计数功能,并将计数的结果返回值主线程显示,来记录多线程的使用方法。
代码如下:
myThread.h如下,注意:不能省略Q_OBJECT,#include<QObject>,因为这是信号槽 的基础。
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include<QObject>
#include<QThread>
#include<qDebug>
class myThread : public QThread
{
Q_OBJECT
public:
myThread();
void run() override;
void stop();
private:
volatile bool isStop ;
static int num;
signals:
void mySignal(int num);
};
#endif // MYTHREAD_H
myThread.cpp
#include "mythread.h"
int myThread::num = 0;
myThread::myThread()
{
isStop = false;
}
void myThread::run()
{
while(!isStop)
{
num++;
QThread::sleep(1);
qDebug()<<"num "<<num;
emit mySignal(num);
}
isStop = false;
}
void myThread::stop()
{
isStop = true;
}
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include"mythread.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = nullptr);
~Dialog();
private slots:
void on_startBtn_clicked();
void on_pauseBtn_clicked();
void on_stopBtn_clicked();
void display(int num);
private:
Ui::Dialog *ui;
myThread *myth;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
myth = new myThread();
connect(myth,SIGNAL(mySignal(int)),this,SLOT(display(int)),Qt::DirectConnection);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_startBtn_clicked()
{
if(!myth->isRunning())
myth->start();
qDebug()<<"main ThreadID :"<<QThread::currentThreadId();
}
void Dialog::on_pauseBtn_clicked()
{
myth->stop();
}
void Dialog::on_stopBtn_clicked()
{
// myth->terminate();
myth->quit();
myth->wait();
}
void Dialog::display(int num)
{
ui->lcdNumber->display(num);
}
main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
运行结果如下图: