2014-10-01 109 views
0

我在Qt C++中遇到了QTimer的問題,在我的代碼中沒有調用timeoutHandler()。任何人都可以告訴我爲什麼以及如何修復它?Qt C++ QTimer不會調用處理程序

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++; 
} 
+1

試着讓你的handleTimeout非靜態? – 2014-10-01 13:02:53

回答

5

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 */ 
} 
0

要更新Googie回答您還可以使用從C++ 11的λ:

QTimer::singleShot(10000, [=]() { 
      // Handle timeout here 
}); 
相關問題