QT多线程下,信号槽分别在什么线程中执行,如何控制?

可以通过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_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    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界面
在这里插入图片描述
输出结果:(以下依次为按钮从左到右的结果)
在这里插入图片描述

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值