可以通过connect的第五个参数进行控制信号槽执行时所在的线程
connect有几种连接方式,直接连接、队列连接和 自动连接
直接连接(Qt::DirectConnection):信号槽在信号发出者所在的线程中执行
队列连接(Qt::QueuedConnection):信号在信号发出者所在线程中执行,槽函数在信号接收者所在线程中执行
自动连接(Qt::AutoConnection):多线程时队列连接函数,单线程时为直接连接。
示例:
mainwind.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include "testthread.h"
#include <QMainWindow>
#include <QThread>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;TestThread* thread1;QThread* th1;private slots:void Test();
};
#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() << "主线程ID" << QThread::currentThreadId();thread1 = new TestThread;th1 = new QThread;thread1->moveToThread(th1);connect(this,&MainWindow::destroyed,this,[=](){thread1->deleteLater();});th1->start();connect(ui->pushButton,&QPushButton::clicked,thread1,&TestThread::count,Qt::DirectConnection);connect(ui->pushButton_2,&QPushButton::clicked,thread1,&TestThread::count,Qt::QueuedConnection);connect(ui->pushButton_3,&QPushButton::clicked,thread1,&TestThread::count,Qt::AutoConnection);connect(ui->pushButton_4,&QPushButton::clicked,this,&MainWindow::Test,Qt::AutoConnection);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::Test()
{qDebug() << "线程ID:" << QThread::currentThreadId();
}
TestThread.h
#ifndef TESTTHREAD_H
#define TESTTHREAD_H#include <QObject>class TestThread : public QObject
{Q_OBJECT
public:explicit TestThread(QObject *parent = nullptr);public slots:void count();
};#endif // TESTTHREAD_H
TestThread.cpp
#include "testthread.h"
#include <QDebug>
#include <QThread>
#include <QDebug>TestThread::TestThread(QObject* parent) : QObject(parent)
{}void TestThread::count()
{qDebug() << "线程ID:" << QThread::currentThreadId() ;}
ui界面
输出结果:(以下依次为按钮从左到右的结果)