在QThread中启动QTimer [英] Starting QTimer In A QThread

查看:2150
本文介绍了在QThread中启动QTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在特定的线程启动一个QTimer。但是,计时器似乎没有执行,什么也没有打印输出。是与定时器,插槽还是线程有关?

I am trying to start a QTimer in a specific thread. However, the timer does not seem to execute and nothing is printing out. Is it something to do with the timer, the slot or the thread?

main.cpp

    #include "MyThread.h"
    #include <iostream>
    using namespace std;

    int main(int argc, char *argv[]) {
        MyThread t;
        t.start();
        while(1);
    }

MyThread.h

MyThread.h

    #ifndef MYTHREAD_H
    #define MYTHREAD_H

    #include <QTimer>
    #include <QThread>
    #include <iostream>

    class MyThread : public QThread {
        Q_OBJECT
    public:
        MyThread();
    public slots:
        void doIt();
    protected:
        void run();
    };

    #endif  /* MYTHREAD_H */

MyThread.cpp

MyThread.cpp

    #include "MyThread.h"

    using namespace std;

    MyThread::MyThread() {
        moveToThread(this);
    }

    void MyThread::run() {
        QTimer* timer = new QTimer(this);
        timer->setInterval(1);
        timer->connect(timer, SIGNAL(timeout()), this, SLOT(doIt()));
        timer->start();
    }

    void MyThread::doIt(){
        cout << "it works";
    }


推荐答案

在链接中)你做错了:


  1. 你正在混合对象持有线程数据与另一个对象c> doIt())。 cb> cb> 更糟糕的是,你在覆盖运行方法,而不考虑它在做什么。

  1. You are mixing the object holding thread data with another object (responsible of doIt()). They should be separated.
  2. There is no need to subclass QThread in your case. Worse, you are overriding the run method without any consideration of what it was doing.

这部分代码应该足够了

QThread* somethread = new QThread(this);
QTimer* timer = new QTimer(0); //parent must be null
timer->setInterval(1);
timer->moveToThread(somethread);
//connect what you want
somethread->start();

现在(Qt版本> = 4.7)默认 QThread run()方法中启动事件循环。为了在一个线程内部运行,你只需要移动对象。 阅读文档...

Now (Qt version >= 4.7) by default QThread starts a event loop in his run() method. In order to run inside a thread, you just need to move the object. Read the doc...

这篇关于在QThread中启动QTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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