在 QThread 中启动 QTimer

Starting QTimer In A QThread(在 QThread 中启动 QTimer)
本文介绍了在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Unresolved external symbol quot;public: virtual struct QMetaObject const * __thiscall Parent(未解析的外部符号“public: virtual struct QMetaObject const * __thiscall Parent)
QVector vs QList(QVector 与 QList)
How to create/read/write JSON files in Qt5(如何在 Qt5 中创建/读取/写入 JSON 文件)
Qt: How do I handle the event of the user pressing the #39;X#39; (close) button?(Qt:如何处理用户按下“X(关闭)按钮的事件?)
STL or Qt containers?(STL 还是 Qt 容器?)
Sort filenames naturally with Qt(使用 Qt 自然地对文件名进行排序)