//工作类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
来源:CSDN
作者:smartDMer
链接:https://blog.csdn.net/smartgps2008/article/details/104571629