简体   繁体   中英

Qt C++ QTimer does not call handler

I've got problem with QTimer in Qt C++, in my code timeoutHandler() is not called. Can anyone tell me why and how I can fix it?

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 requires Qt event loop to work. When you enter the 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). Here's how you should do it:

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

To update answer from Googie you can use also lambda from C++11:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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