需继承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();
}
主线程直接调用与信号触发的槽函数线程不同