QT多线程开发(二)——QT开启多个子线程方法
使用movetoThread方法。、
1、新建项目
新建MainWindow和MyThread。
2、代码如下
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include "mythread.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
QThread *m_Thread;
MyThread *m_MyThread;
signals:
void signal01();
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug()<<"主线程号:"<<QThread::currentThread()<<QThread::currentThreadId();
}
MainWindow::~MainWindow()
{
delete ui;
}
//每点击一次按钮,新建一个子线程
void MainWindow::on_pushButton_clicked()
{
qDebug()<<"新建线程";
m_Thread = new QThread();
m_MyThread = new MyThread();
m_MyThread->moveToThread(m_Thread);
connect(m_Thread,&QThread::finished,m_Thread,&QThread::deleteLater);
connect(this,&MainWindow::signal01,m_MyThread,&MyThread::doSomething);
m_Thread->start();
}
void MainWindow::on_pushButton_2_clicked()
{
qDebug()<<"信号";
emit signal01();
}
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
class MyThread : public QObject
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
signals:
public slots:
void doSomething();
};
#endif // MYTHREAD_H
mythread.cpp
#include "mythread.h"
#include <QDebug>
#include <QThread>
MyThread::MyThread(QObject *parent) : QObject(parent)
{
qDebug()<<"MyThread"<<QThread::currentThread();
}
void MyThread::doSomething()
{
qDebug()<<"子线程号:"<<QThread::currentThread();
}
运行效果
不足之处
这里没有将每次新建的子线程进行记录,会导致信号触发到所有新建的子线程中。下一步使用Vector将子线程记录下来,区分新建的子线程。