Qt C ++ QTimer不调用处理程序

时间:2014-10-01 13:00:51

标签: c++ qt

我在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++;
}

2 个答案:

答案 0 :(得分: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 */
}

答案 1 :(得分:0)

要更新Googie的答案,您还可以使用C ++ 11中的lambda:

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