代码如下:
MyObject.h
#pragma once
#include <QObject>
#include <QEvent>
const QEvent::Type CustomEvent_Login = (QEvent::Type)5001; //! 建议用5000以上唯一的标识
class MyObject : public QObject
{
Q_OBJECT
public:
MyObject();
~MyObject();
protected slots:
void Started();
void Timeout();
private:
void customEvent(QEvent *e); //! 重载QObject的续虚函数
};
MyObject.cpp
#include "MyObject.h"
#include <QDebug>
#include <QThread>
MyObject::MyObject()
{
}
MyObject::~MyObject()
{
}
void MyObject::Started()
{
qDebug() << "Started:" << (qlonglong)QThread::currentThreadId();
}
void MyObject::Timeout()
{
qDebug() << "Timeout:" << (qlonglong)QThread::currentThreadId();
}
void MyObject::customEvent(QEvent *e)
{
if (e->type() == CustomEvent_Login)//捕获消息
{
qDebug() << QString("[%1]catch the event: %2!").arg((qlonglong)QThread::currentThreadId()).arg(e->type());
}
}
Main.cpp
#include <QtCore/QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QObject>
#include <QTimer>
#include "MyObject.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "main:" << (qlonglong)QThread::currentThreadId();
//! 业务逻辑对象
MyObject* myObj = new MyObject;
//! 线程-->新的线程
QThread *thread = new QThread();
//! 定时器
QTimer *timer = new QTimer();
//! 把业务逻辑对象设置进线程,不要把Qthread放进自己线程,这样的写法不建议。
myObj->moveToThread(thread);
//! 线程启动
thread->start();
//! 绑定的时候最好设置QueuedConnection。这样就允许在myObj线程执行,否则可能会在主线程执行。
//! 如果希望不要再子线程执行,用DirectConnection。
QObject::connect(thread, SIGNAL(started()), myObj, SLOT(Started()), Qt::QueuedConnection);
QObject::connect(timer, SIGNAL(timeout()), myObj, SLOT(Timeout()), Qt::QueuedConnection);
//! 定时器启动
timer->start(1000);
//! 发送事件
QCoreApplication::postEvent(myObj, new QEvent(CustomEvent_Login));
qDebug() << QString("[%1]send the event: %2!")
.arg((qlonglong)QThread::currentThreadId())
.arg(CustomEvent_Login);
//! MyObject::Started/MyObject::Timeout/都会在同一个子线程调用。
return a.exec();
}