需继承QObject
#ifndef MOVETOTHREAD_H
#define MOVETOTHREAD_H
#include <QObject>
#include <QThread>
#include <QDebug>
class movetothreadTest:public QObject
{
Q_OBJECT
private:
QThread m_Thread;
public:
explicit movetothreadTest(QObject *parent = nullptr);
~movetothreadTest();
signals:
void signalFunc(void);
public slots:
void EmitSingalFunc(void);
void testFunc(void);
};
#endif // MOVETOTHREAD_H
#include "movetothreadTest.h"
movetothreadTest::movetothreadTest(QObject *parent)
: QObject(parent)
{
moveToThread(&m_Thread);
m_Thread.start();
connect(this,&movetothreadTest::signalFunc,this,&movetothreadTest::testFunc);
}
movetothreadTest::~movetothreadTest()
{
m_Thread.quit();
m_Thread.wait();
}
void movetothreadTest::EmitSingalFunc(void)
{
emit signalFunc();
}
void movetothreadTest::testFunc(void)
{
qDebug()<<"testFunc thread:"<<QThread::currentThreadId()<<endl;
}
#include <QCoreApplication>
#include "movetothreadTest.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
movetothreadTest M;
qDebug()<<"main thread:"<<QThread::currentThreadId()<<endl;
M.testFunc();
M.EmitSingalFunc();
return a.exec();
}
主线程直接调用与信号触发的槽函数线程不同


该博客介绍了如何在C++中使用QObject的moveToThread方法将对象移动到新线程,以便实现多线程编程。示例代码创建了一个movetothreadTest类,它继承自QObject,并定义了信号和槽函数,确保信号触发的槽函数在不同的线程中运行。在main函数中,创建了movetothreadTest对象并启动其所在线程,展示了主线程与信号槽线程的并发执行。

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



