(Qt) QThread 信号槽所在线程

💁🏻前言

在 Qt 中用一套自己的封装的多线程操作。

其中一种方式是继承 QThread 并实现 void run(); 方法使用 void start(); 启动,这是一种很常见的线程的封装方式。这种方式在 java 中也是这么设计的。

但是由于 Qt 的高度封装性和框架整体性,很多特性都是开发者自己测试出来的。

其中 QThread 配合信号槽的特性就是本文要观察的重点。

💁🏻Code

这里放一份基本的code,后面的观察都是基于具体 void QThread::run(); 的修改的观察。

本文下面默认的外部线程值得就是在 main() 中一致的线程。

💁🏻‍♂️Code

目录

C:.
└─mythread
        main.cpp
        mythread.cpp
        mythread.h
        mythread.pro

mythread.pro

QT = core

CONFIG += c++17 cmdline

SOURCES +=      \
    main.cpp    \
    mythread.cpp

HEADERS += \
    mythread.h

main.cpp

只负责创建我们观察的实例

#include <QCoreApplication>
#include <QDebug>
#include <QThread>

#include "mythread.h"

int main(int argc, char* argv[]) {
   
   
    QCoreApplication a(argc, argv);
    qDebug() << "Main Thread" << QThread::currentThread();

    MyThread myth;
    qDebug() << "Object-Thread" << myth.thread();

    return a.exec();
}

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class MyThread : public QThread {
   
   
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = nullptr);

protected:
    void run() override;

signals:
    void signal_test();
};

#endif  // MYTHREAD_H

mythread.cpp

在构造中就启动线程。(主要是想把所有操作都几种在一个文件中,不影响测试的效果个逻辑)

在槽函数的事件中,再次发出信号,查看连续的信号槽的效果。

#include "mythread.h"

#include <QDebug>
#include <QThread>
#include <QTimer>

MyThread::MyThread(QObject *parent) : QThread{
   
   parent} {
   
   
    qDebug() << QString("Construction-Line[%1]").arg(__LINE__) << QThread::currentThread();
    start();

    // QTimer::singleShot(100, this, [this]() { emit signal_test(); });
}

void MyThread::run() {
   
   
    qDebug() << QString("Run-Line[%1]")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天赐细莲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值