简体   繁体   English

Qt:等待超时管理信号

[英]Qt: waiting for a signal with timeout management

I'm looking for a simple way to wait for an object to emit signal with timeout management using Qt. 我正在寻找一种简单的方法来等待一个对象使用Qt进行超时管理来发出信号。

Is there an easy way to do that using Qt classes? 使用Qt类有一种简单的方法吗?

Here is an example of application: 这是一个应用示例:

QLowEnergyController controller(remoteDevice);
controller.connectToDevice();
// now wait for controller to emit connected() with a 1sec timeout

Based on this post , here is a class (encapsulating @EnOpenUK solution) and proposing a wait function with timeout management. 基于这篇文章 ,这里有一个类(封装@EnOpenUK解决方案)并提出了一个带有超时管理的等待函数。

Header file: 头文件:

#include <QEventLoop>
class WaitForSignalHelper : public QObject
{
    Q_OBJECT
public:
    WaitForSignalHelper( QObject& object, const char* signal );

    // return false if signal wait timed-out
    bool wait();

public slots:
    void timeout( int timeoutMs );

private:
    bool m_bTimeout;
    QEventLoop m_eventLoop;
};

Implementation file: 实施文件:

#include <QTimer>
WaitForSignalHelper::WaitForSignalHelper( QObject& object, const char* signal ) : 
    m_bTimeout( false )
{
    connect(&object, signal, &m_eventLoop, SLOT(quit()));
}

bool WaitForSignalHelper::wait( int timeoutMs )
{
    QTimer timeoutHelper;
    if ( timeoutMs != 0 ) // manage timeout
    {
        timeoutHelper.setInterval( timeoutMs );
        timeoutHelper.start();
        connect(&timeoutHelper, SIGNAL(timeout()), this, SLOT(timeout()));
    }
    // else, wait for ever!

    m_bTimeout = false;

    m_eventLoop.exec();

    return !m_bTimeout;
}

void WaitForSignalHelper::timeout()
{
    m_bTimeout = true;
    m_eventLoop.quit();
}

Example: 例:

QLowEnergyController controller(remoteDevice);
controller.connectToDevice();
WaitForSignalHelper helper( controller, SIGNAL(connected()) );
if ( helper.wait( 1000 ) )
    std::cout << "Signal was received" << std::endl; 
else
    std::cout << "Signal was not received after 1sec" << std::endl;

Note that setting timeout parameter to 0 makes the object wait for ever...could be useful. 请注意,将timeout参数设置为0会使对象永远等待...可能很有用。

In Qt 5, the QtTest header has QSignalSpy::wait , to wait until a signal is emitted or a timeout (in milliseconds) occurs. 在Qt 5中, QtTest头具有QSignalSpy :: wait ,等待直到发出信号或发生超时(以毫秒为单位)。

auto controller = QLowEnergyController{remoteDevice};
auto spy = QSignalSpy{*controller, SIGNAL(connected())};
controller.connectToDevice();
spy.wait(1000);

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

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