简体   繁体   English

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

[英]Qt C++ QTimer does not call handler

I've got problem with QTimer in Qt C++, in my code timeoutHandler() is not called. 我在Qt C ++中遇到了QTimer问题,在我的代码中未调用timeoutHandler()。 Can anyone tell me why and how I can fix it? 谁能告诉我原因以及如何解决?

Test.h 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 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 requires Qt event loop to work. QTimer需要Qt事件循环才能工作。 When you enter the while(!timeOuted); 当您输入while(!timeOuted); , you block the current thread endlessly and the Qt's event loop has no chance to take any action (like calling your handler for the timer). ,您将无限期地阻塞当前线程,并且Qt的事件循环没有机会执行任何操作(例如,为计时器调用处理程序)。 Here's how you should do it: 这是您应该如何做:

Test.h: 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: TEST.CPP:

void Test::run()
{
    QTimer::singleShot(3000, this, SLOT(handleTimeout()));
}

void Test::handleTimeout()
{
    static int i = 0;
    qDebug() << "TimeOuted " << i++;

    /* some work */
}

To update answer from Googie you can use also lambda from C++11: 要更新Googie的答案,您还可以使用C ++ 11中的lambda:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM