簡體   English   中英

Qt:等待超時管理信號

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

我正在尋找一種簡單的方法來等待一個對象使用Qt進行超時管理來發出信號。

使用Qt類有一種簡單的方法嗎?

這是一個應用示例:

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

基於這篇文章 ,這里有一個類(封裝@EnOpenUK解決方案)並提出了一個帶有超時管理的等待函數。

頭文件:

#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;
};

實施文件:

#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();
}

例:

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;

請注意,將timeout參數設置為0會使對象永遠等待...可能很有用。

在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