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);
相关文章:
- Qt VTK交互风格的信号到小部件
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 当vector是tje全局变量时,c++中vector的内存管理
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何在没有信号的情况下从C++执行QML插槽
- 线程之间的布尔停止信号
- 如何维护资源管理器项目视图中当前可见的项目列表
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 有可能在信号处理程序中设置promise吗
- 资源管理设计模式
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 使用"Task"函数指针队列定义作业管理器
- 在条件变量中触发错误信号的频率是多少
- 用户类中的多签名信号管理
- 使用信号和线程的事件管理器
- Boost信号连接管理
- 你如何处理内存管理和信号/插槽
- Qt:等待具有超时管理的信号