A.Danesh
A.Danesh

Reputation: 854

How to declare New-Signal-Slot syntax in Qt 5 as a parameter to function

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?

Upvotes: 6

Views: 2004

Answers (2)

Nejat
Nejat

Reputation: 32645

You can simply use QSignalSpy to wait for a signal to be emitted by :

QSignalSpy spy(sender, SIGNAL(someSignal()));
spy.wait(timeOut);

Or (This is possible in Qt 5.4) :

QSignalSpy spy(sender, &SomeObject::someSignal);
spy.wait(timeOut);

If you want to implement it in a function :

bool waitForSignal(const typename QtPrivate::FunctionPointer<Func>::Object *sender, Func signal, int timeOut = 5000/*ms*/)
{
   QSignalSpy spy(sender, signal);
   return spy.wait(timeOut);
}

Do not forget to add the relevant module in qmake :

QT += testlib

Upvotes: 0

Meefte
Meefte

Reputation: 6735

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);

Upvotes: 6

Related Questions