QObject :: startTimer:计时器只能与以QThread开头的线程一起使用 [英] QObject::startTimer: Timers can only be used with threads started with QThread

查看:2473
本文介绍了QObject :: startTimer:计时器只能与以QThread开头的线程一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在工作线程的事件循环中启动Timer,但出现此错误: QObject::startTimer: Timers can only be used with threads started with QThread

I am trying to start a Timer in a worker thread's event loop, but I get this error: QObject::startTimer: Timers can only be used with threads started with QThread

这有什么问题?

#include <QObject>
#include <QThread>
#include <QTimer>

class A : public QObject
{
    Q_OBJECT
public:
    A();

private:
    QThread m_workerThread;
    QTimer m_myTimer;

};

A::A()
{
    this->moveToThread(&m_workerThread);
    m_myTimer.moveToThread(&m_workerThread);
    m_workerThread.start();
    m_myTimer.start(1000);
}

推荐答案

可以在任何地方初始化计时器,但是要在线程启动时立即启动(将其附加到

Initialize your timer anywhere, but start it right when the thread is started (attach it to QThread::started signal):

class A : public QObject
{
    Q_OBJECT
public:
    A();

private slots:
    void started();
    void timeout();

private:
    QThread m_workerThread;
    QTimer m_myTimer;
};

A::A()
{
    moveToThread(&m_workerThread);

    connect(&m_workerThread, SIGNAL(started()), this, SLOT(started()));
    connect(&m_myTimer, SIGNAL(timeout()), this, SLOT(timeout()));

    m_myTimer.setInterval(1000);
    m_myTimer.moveToThread(&m_workerThread);

    m_workerThread.start();
}

void A::started()
{
    timer.start();
}

void A::timeout()
{
    // timer handler
}

这篇关于QObject :: startTimer:计时器只能与以QThread开头的线程一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆