如何声明Qt 5中的New-Signal-Slot语法作为函数的参数 [英] How to declare New-Signal-Slot syntax in Qt 5 as a parameter to function

查看:615
本文介绍了如何声明Qt 5中的New-Signal-Slot语法作为函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过信号或槽(成员函数,Qt 5中的新语法)作为函数的参数,然后调用 connect



例如

:不能编译 - PointerToMemberFunction

code>是我的问题。

  bool waitForSignal(const QObject * sender,PointerToMemberFunction ??? signal,int timeOut = 5000 / * ms * /)
{
if(sender == nullptr)
return true;
bool isTimeOut = false;
QEventLoop loop;
QTimer timer;
timer.setSingleShot(true);
QObject :: connect(& timer,& QTimer :: timeout,
[& loop,& isTimeOut]()
{
loop.quit
isTimeOut = true;
});
timer.start(timeOut);
QObject :: connect(sender,signal,& loop,& QEventLoop :: quit);
loop.exec();
timer.stop();
return!isTimeOut;
}

有没有办法将信号列表传递给此函数进行连接? / p>

解决方案

您应该创建模板:

  template< typename Func> 
void waitForSignal(const typename QtPrivate :: FunctionPointer< Func> :: Object * sender,Func signal){
QEventLoop loop;
connect(sender,signal,& loop,& QEventLoop :: quit);
loop.exec();
}

用法:

  waitForSignal(button,& QPushButton :: clicked); 


How can I pass signal or slot (member-function, new syntax in Qt 5) as a parameter to function and then call connect?

e.g. I want to write a function that waits for a signal.

Note: It is not compile - PointerToMemberFunction is my question.

bool waitForSignal(const QObject* sender, PointerToMemberFunction??? signal, int timeOut = 5000/*ms*/)
{
  if (sender == nullptr)
    return true;
  bool isTimeOut = false;
  QEventLoop loop;
  QTimer timer;
  timer.setSingleShot(true);
  QObject::connect(&timer, &QTimer::timeout,
    [&loop, &isTimeOut]()
    {
      loop.quit();
      isTimeOut = true;
    });
  timer.start(timeOut);
  QObject::connect(sender, signal, &loop, &QEventLoop::quit);
  loop.exec();
  timer.stop();
  return !isTimeOut;
}

Is there any way to pass list of signals to this function for connection?

解决方案

You should create template:

template<typename Func>
void waitForSignal(const typename QtPrivate::FunctionPointer<Func>::Object *sender, Func signal) {
    QEventLoop loop;
    connect(sender, signal, &loop, &QEventLoop::quit);
    loop.exec();
}

Usage:

waitForSignal(button, &QPushButton::clicked);

这篇关于如何声明Qt 5中的New-Signal-Slot语法作为函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆