💁🏻前言
在 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]")

最低0.47元/天 解锁文章
663

被折叠的 条评论
为什么被折叠?



