一、功能说明
1、通过继承QRunnable,重写run的方式实现多线程
2、点击“开始”按钮启动子线程;
二、项目创建
1、新建Qt Widgets Application应用,名称为Runnable,基类选择QMainWindow;
2、MainWindow.ui中放入一个Push Button按钮,第一个text改为“开始”,objectNme改为startPushButton;
3、添加新的C++类,名称为MyRunnable,基类设置为QRunnable
4、注:
QRunnable的使用方式与QThread类似,但是QRunnable不能使用信号槽,可以使用QMetaObject::invokeMethod()
三、代码展示
1、myrunnable.h
#ifndef MYRUNNABLE_H
#define MYRUNNABLE_H#include <QRunnable>
#include <QWidget>class MyRunnable : public QRunnable
{
public:explicit MyRunnable();~MyRunnable();protected:void run();
};#endif // MYRUNNABLE_H
2、myrunnable.cpp
#include "myrunnable.h"
#include <QDebug>
#include <QThread>MyRunnable::MyRunnable()
{qDebug() << "MyRunnable(): " << QThread::currentThreadId();
}MyRunnable::~MyRunnable()
{qDebug() << "~MyRunnable(): " << QThread::currentThreadId();
}void MyRunnable::run()
{qDebug() << "MyRunnable::run()" << QThread::currentThreadId();
}
3、mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include "myrunnable.h"namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_startPushButton_clicked();private:Ui::MainWindow *ui;MyRunnable *m_myRunnable;
};#endif // MAINWINDOW_H
4、mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
#include <QDebug>
#include <QThreadPool>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{ui->setupUi(this);m_myRunnable = new MyRunnable;qDebug() << "MainWindow() " << QThread::currentThreadId();
}MainWindow::~MainWindow()
{if(!m_myRunnable){delete m_myRunnable;m_myRunnable = nullptr;}delete ui;
}void MainWindow::on_startPushButton_clicked()
{qDebug() << "on_startPushButton_clicked() " << QThread::currentThreadId();QThreadPool::globalInstance()->start(m_myRunnable);
}
四、运行测试
运行程序,点击开始,输出框输出如下信息