[英]Qt C++ QTimer does not call handler
我在Qt C ++中遇到了QTimer問題,在我的代碼中未調用timeoutHandler()。 誰能告訴我原因以及如何解決?
Test.h
class Test : public QObject
{
Q_OBJECT
private:
static bool timeOuted;
public:
explicit Test(QObject *parent = 0);
virtual ~Test();
public slots:
static void handleTimeout();
};
TEST.CPP
void Test::run()
{
QTimer::singleShot(3000, this, SLOT(handleTimeout()));
while(!timeOuted);
if(timeOuted)
{
timeOuted = false;
}
else
{
/* some work */
}
}
bool Test::timeOuted = false;
void Test::handleTimeout()
{
static int i = 0;
timeOuted = true;
qDebug() << "TimeOuted " << i++;
}
QTimer
需要Qt事件循環才能工作。 當您輸入while(!timeOuted);
,您將無限期地阻塞當前線程,並且Qt的事件循環沒有機會執行任何操作(例如,為計時器調用處理程序)。 這是您應該如何做:
Test.h:
class Test : public QObject
{
Q_OBJECT
public:
explicit Test(QObject *parent = 0);
virtual ~Test();
void run(); // <-- you missed this
private slots: // <-- no need to make this slot public
void handleTimeout(); // <-- why would you make it static?!
};
TEST.CPP:
void Test::run()
{
QTimer::singleShot(3000, this, SLOT(handleTimeout()));
}
void Test::handleTimeout()
{
static int i = 0;
qDebug() << "TimeOuted " << i++;
/* some work */
}
要更新Googie的答案,您還可以使用C ++ 11中的lambda:
QTimer::singleShot(10000, [=]() {
// Handle timeout here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.