Qt5: connect: How to use 'connect' in case the slot has less parameters than the signal

Viewed 1322

Task is to connect from one signal with one parameter to a slot with zero parameters. With the "old" Qt4-way of connect it works like this

connect(object1, SIGNAL(signal(int param)), object2, SLOT(slot()))

But what if I want to use the type-safe Qt5-connects?

The documentation just mentions the cases with:

  • connect to default parameters in slot

  • and using the above-mentioned way of the stringbased connect.

3 Answers

The Qt5-style connect mechanism ignores extra-arguments of the signal just like you could specify in the Qt4-style:

The signals and slots mechanism is type safe: The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.) Since the signatures are compatible, the compiler can help us detect type mismatches when using the function pointer-based syntax. The string-based SIGNAL and SLOT syntax will detect type mismatches at runtime.

From the Qt Docs (emphasis mine).

So you can use the new style like this:

connect(&object1, &ClassObject1::signal, &object2, &ClassObject2::slot);

You can connect as the Qt4-Way without problems. The only thing you can't do is connect with the slot having less params.

Nevermind, found a way to handle this without declaring and defining an additional slot: the solution is to use a lambda, to fizzle out the additionals parameter(s).

Example (in case of object2 is our own project (this). Following the style of the naming like in the question:

connect(object1, &Object1::signal, [this](int) { slot(); } );
Related