//工作類test moveToThread
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0) : QObject(parent) {}
signals:
void doSomething();
public slots:
void trigger()
{
qDebug() << "moveToThread Worker::trigger()";
emit doSomething();
}
};
//主線程
void MainWindow::test_moveToThread()
{//需要使用指針變量,否則退出該函數就析構了
QThread *thread = new QThread;
Worker *work = new Worker;
QTimer *timer = new QTimer;
timer->setInterval(2000);
timer->moveToThread(thread);
work->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), timer, SLOT(start()));
QObject::connect(work, SIGNAL(doSomething()), this, SLOT(slot_timer_movetothread()));
QObject::connect(timer, SIGNAL(timeout()), work, SLOT(trigger()));
thread->start();
//QMetaObject::invokeMethod(&timer, "start", Qt::QueuedConnection); //timer->start()
//QMetaObject::invokeMethod(&timer, "start", Qt::QueuedConnection , Q_ARG(int, 1000 )); //timer->start(200)
}
//Try
//QMetaObject::invokeMethod(&timer, "start", Qt::QueuedConnection); //timer->start()
//if you want to start timer immediately
//Or
//QMetaObject::invokeMethod(&timer, "start", Qt::QueuedConnection , Q_ARG(int, 1000 )); //timer->start(200)
//if you want to start timer after 1000s
//In the Non-GUI thread (QThread or Pthread Callback)
void MainWindow::slot_timer_movetothread()
{
qDebug() << "moveToThread MainWindow::slot_timer_movetothread()";
}
//來源:https://stackoverflow.com/questions/15835267/qthread-and-qtimer
//參考:https://blog.csdn.net/weixin_30415113/article/details/99479435
Qt:QThread中直接使用QTimer,不封裝QThread
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.