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

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

eg. I want to write a function that is waiting for a signal.

Note : it does 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 a way to pass a list of signals to this function for a connection?

+6
source share
2 answers

You should create a 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(); } 

Using:

 waitForSignal(button, &QPushButton::clicked); 
+6
source

You can simply use QSignalSpy to expect the signal to emit:

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

Remember to add the appropriate module to qmake:

 QT += testlib 
0
source

Source: https://habr.com/ru/post/980468/


All Articles