线程工作者Qt中的计时器

时间:2017-12-22 11:22:07

标签: c++ multithreading qt timer

我试图在工人阶级使用计时器。这是我的工人阶级:

Worker.h

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = nullptr);

signals:
    void finished(void);

public slots:
    void process(void);
    void test(void);

private:
    QMutex m_mutex;

};

Worker.cpp

void Worker::process(void)
{
    qDebug() << "worker process";       //This works
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(test()));

    forever
    {

    }
}

void Worker::test(void)
{
    qDebug() << "test123";   //This does not work
}

我在新线程中启动此worker类:​​

QThread *thread = new QThread;
    Worker *worker = new Worker;
    worker->moveToThread(thread);

    QObject::connect(thread, SIGNAL(started()), worker, SLOT(process()), Qt::QueuedConnection);
    QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    QObject::connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
    QObject::connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));

    thread->start();

问题是来自timer的{​​{1}}不起作用。我是否需要以特殊方式在新线程中初始化此计时器?

1 个答案:

答案 0 :(得分:1)

创建计时器后,您需要调用void QTimer::start(int msec) or void QTimer::start()。你也不需要&#34;永远&#34;在你的process()槽中。

请改为尝试:

void Worker::process(void)
{
    qDebug() << "worker process";       //This works
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(test()));
    timer->start(1000); // Fire timer timeout each 1000ms.
}