本文主要是介绍Qt:QThread中直接使用QTimer,不封装QThread,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//工作类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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!