小编Tud*_*scu的帖子

在QThread中启动QTimer

我试图在特定的线程中启动QTimer.但是,计时器似乎没有执行,也没有打印出来.是与计时器,插槽还是线程有关?

main.cpp中

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

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

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 */
Run Code Online (Sandbox Code Playgroud)

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 …
Run Code Online (Sandbox Code Playgroud)

c++ qt multithreading timer qthread

15
推荐指数
3
解决办法
4万
查看次数

标签 统计

c++ ×1

multithreading ×1

qt ×1

qthread ×1

timer ×1