6

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?

skyaakash
  • 161
  • 2
  • 9

2 Answers2

11

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.
Community
  • 1
  • 1
CJCombrink
  • 3,738
  • 1
  • 22
  • 38
  • 1
    I think it's safer to [provide explicit template arguments to `connect<>()`](/a/37302949) than to `static_cast` the member pointer. – Toby Speight Aug 05 '16 at 10:06
  • @TobySpeight I was not aware of this syntax, thanks. I can see how it can be deduced when looking at the implementation of `QObject::connect` but it seems like it is undocumented, especially when looking at the documentation on [QObject::connect()](http://doc.qt.io/qt-5/qobject.html#connect-3) (the docs hide the use of templates) – CJCombrink Aug 10 '16 at 08:34
1

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

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299