main.cpp
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include "hello.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "main thread id" << QThread::currentThreadId();
QThread thread;
thread.start();
Hello test;
test.moveToThread(&thread);
test.testThread("直接调用");
// 子线程调用
emit test.callTheadFun("通过emit调用");
// 子线程调用
QMetaObject::invokeMethod(&test, "testThread", Qt::QueuedConnection, Q_ARG(QString, "通过invokeMethod调用"));
return a.exec();
}
hello.h
#ifndef HELLO_H
#define HELLO_H
#include <QObject>
#include <QTimer>
class Hello : public QObject
{
Q_OBJECT
public:
explicit Hello(QObject *parent = nullptr);
signals:
void callTheadFun(QString msg);
public slots:
void testThread(const QString &msg);
void testConnect();
private:
QTimer *m_timer;
};
#endif // HELLO_H
hello.cpp
#include <QDebug>
#include <QThread>
#include "hello.h"
Hello::Hello(QObject *parent)
: QObject(parent)
, m_timer(new QTimer)
{
// 定时器中,直接调用lambda函数时, 主线程调用
connect(m_timer, &QTimer::timeout, [=](){
qDebug() << "定时器中,直接调用lambda函数时, thread id" << QThread::currentThreadId();
});
// 定时器中,将lambda作为成员函数调用时, 子线程调用
connect(m_timer, &QTimer::timeout, this, [=](){
qDebug() << "定时器中,将lambda作为成员函数调用时, thread id" << QThread::currentThreadId();
});
// 定时器中,调用成员函数,子线程调用
connect(m_timer, &QTimer::timeout, this, &Hello::testConnect);
m_timer->setSingleShot(true);
m_timer->start(1000);
// auto connect, 子线程调用
connect(this, &Hello::callTheadFun, this, &Hello::testThread);
}
void Hello::testThread(const QString &msg)
{
qDebug() << "in testThread" << msg << "thread id" << QThread::currentThreadId();
}
void Hello::testConnect()
{
qDebug() << "定时器中,调用成员函数, thread id" << QThread::currentThreadId();
}
测试结果
结论:
将对象放到单独线程中后
- 直接调用对象的方法,方法在主线程中运行
- 通过信号(emit)调用或者invokeMoethod调用,函数在子线程中运行
- 定时器中,直接调用lambda函数时, 函数在主线程调用
- 定时器中,将lambda作为成员函数调用时或者直接调用成员函数时, 函数在子线程运行