Qt 中Qtimer的使用

2 篇文章 1 订阅

1.定时器Timer类

创建一个QTimer对象,将信号timeout()与相应的槽函数相连,然后调用start()函数。接下来,每隔一段时间,定时器便会发出一次timeout()信号。

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);

2.在线程中使用QTimer

void Thread::run()
{
    cTimer = new QTimer();
    cTimer->setInterval(1000);
    connect(cTimer, &QTimer::timeout, this, &Thread::timeoutSlot);
    cTimer->start();
    this->exec();
}

注意:在线程中使用QTimer不能使用new QTimer(this)这样给定时器指定父对象,否则会出现错误。

必须加上exec();否则会出现 QObject::killTimer: Timers cannot be stopped from another thread错误。

3.在线程中使用QTimer 2

TestClass::TestClass(QWidget *parent)
    : QWidget(parent)
{
    m_pThread = new QThread(this);
    m_pTimer = new QTimer();
    m_pTimer->moveToThread(m_pThread);
    m_pTimer->setInterval(1000);
    connect(m_pThread, SIGNAL(started()), m_pTimer, SLOT(start()));
    connect(m_pTimer, &QTimer::timeout, this, &ThreadTest::timeOutSlot, Qt::DirectConnection);
}

  • 3
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值