在qt界面中通过定时器使用多线程的简单方法

最近在做ros平台下的项目,需要用到qt,之前对多线程完全不懂,上网找了一些博客看了一下,最终找到了一种简单使用多线程的方法。
具体可以参考下列博客
[Qt——线程与定时器](https://www.cnblogs.com/hellovenus/p/qt_thread_timer.html)

首先定义一个定时器和线程变量:

 QTimer *plantimer;
 QThread *plantimer_thread;

然后在具体的构造函数中加入下列代码:

// 规划线程
    plantimer_thread = new QThread(this);
    plantimer = new QTimer();
    plantimer->moveToThread(plantimer_thread);//将该定时器放在线程中
    plantimer->setInterval(100);//定时器间隔时间
    connect(plantimer_thread, SIGNAL(started()), plantimer, SLOT(start()));//通过线程开启来触发定时器开启
    connect(plantimer, &QTimer::timeout, this, &IVDecisionDlg::onPlanTimer, Qt::DirectConnection);//信号发出后立即调用槽函数,槽函数在发出信号的线程中执行
    connect(plantimer_thread, &QThread::finished, this, &QObject::deleteLater);//线程结束,自动关闭线程

开启线程:

plantimer_thread->start();

菜鸟的个人实际经历,有不对的地方希望大家指出来,谢谢!

你可能感兴趣的:(qt学习)