Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QObject::startTimer: Timers can only be used with threads started with QThread

Tags:

qt

qthread

qtimer

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

Whats wrong with this?

#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);
}
like image 528
user2950911 Avatar asked Mar 14 '14 08:03

user2950911


1 Answers

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
}
like image 169
gabonator Avatar answered Sep 18 '22 11:09

gabonator