Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In QT, can we have two slots with same name but different arguments?

I have two signals with same name coming from two different classes A and B into class C. Let void SomeSignal() is a signal from class A without any argument. I have another signal void SomeSignal(int) coming from another class.

I need to handle these signals in two different ways in class C. Can I make two slots void SomeSignal() and void SomeSignal(int) in class C?

like image 388
skyaakash Avatar asked Aug 05 '16 07:08

skyaakash


2 Answers

Yes it is valid. But if you do this, you need to handling connecting to the signals/slots differently than the normal way when using the Qt 5 connect syntax.

Look at the following question and answer on how to handle connecting to overloaded signals and slots

So in short, connect as:

connect(a, &A::SomeSignal, this, static_cast<void (C::*)(void)>(&C::SomeSlot));
connect(b, &B::SomeSignal, this, static_cast<void (C::*)(int)>(&C::SomeSlot));

Or if you are using Qt 5.7 use the qOverload helper functions.

Edit: Using explicit template arguments as @TobySpeight pointed out below:

QObject::connect<void(A::*)(), void(C::*)()>(&a, &A::SomeSignal, &c, &C::SomeSlot);
QObject::connect<void(B::*)(int), void(C::*)(int)>(&b, &B::SomeSignal, &c, &C::SomeSlot);
  • Seems like one must specify both template arguments to connect since the slot is overloaded.
like image 131
CJCombrink Avatar answered Sep 28 '22 10:09

CJCombrink


Yes, you can, but if you are handling different stuff coming from completely different classes it's clearer to name those slots differently (remember that there's no relation required between the signals names and the linked slots names).

like image 25
Matteo Italia Avatar answered Sep 28 '22 08:09

Matteo Italia