本文介紹了在 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 :
- 您將保存線程數據的對象與另一個對象(負責
doIt()
)混合在一起.他們應該分開. - 在您的情況下,無需對
QThread
進行子類化.更糟糕的是,您覆蓋了run
方法,而沒有考慮它在做什么.
- You are mixing the object holding thread data with another object (responsible of
doIt()
). They should be separated. - There is no need to subclass
QThread
in your case. Worse, you are overriding therun
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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!