在 QThread 中启动 QTimer

时间:2023-01-02
本文介绍了在 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

    #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";
    }

推荐答案

正如我所评论的(链接中的更多信息),您做错了:

As I commented (further information in the link) you are doing it wrong :

  1. 您将保存线程数据的对象与另一个对象(负责 doIt())混合在一起.他们应该分开.
  2. 在您的情况下,无需对 QThread 进行子类化.更糟糕的是,您覆盖了 run 方法,而没有考虑它在做什么.
  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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用 for Qt 制作无边框窗口 下一篇:使用gdb在Qt Creator中调试时如何避免进入库的源文件?

相关文章

最新文章