如何在Qt 5中声明New-Signal-Slot语法作为参数来运行

A.D*_*esh 6 c++ qt signals-slots qt5

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

例如,我想写一个等待信号的函数.

注意:它不是编译 - PointerToMemberFunction是我的问题.

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Mee*_*fte 6

你应该创建模板:

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

用法:

waitForSignal(button, &QPushButton::clicked);
Run Code Online (Sandbox Code Playgroud)

  • 有效,但请参阅上面的评论.这是私有API. (2认同)