maim.cpp
-------------------------------------------------------------------------------------------------
#include <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();
}
-------------------------------------------------------------------------------------------------
myobject.cpp
-------------------------------------------------------------------------------------------------
#include "myobject.h"
#include <QDebug>
#include <QThread>
MyObject::MyObject()
{
}
void MyObject::Started()
{
qDebug() << "Started:" << (qlonglong)QThread::currentThreadId() ;
}
void MyObject::Timeout()
{
qDebug() << "Timeout:" << (qlonglong)QThread::currentThreadId() ;
}
void MyObject::customEvent(QEvent *e)
{
}
-------------------------------------------------------------------------------------------------
myobject.h
-------------------------------------------------------------------------------------------------
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QObject>
#include <QEvent>
class MyObject : public QObject
{
Q_OBJECT
public:
MyObject();
protected slots:
void Started();
void Timeout();
private:
void customEvent(QEvent *e); //! 重载QObject的续虚函数重要,重要,重要
};
#endif // MYOBJECT_H