Qt 5 introduced a new signal-slot syntax using pointers to member functions, aimed at improving readability and extensibility. However, it presented challenges when connecting to overloaded signals.
In an attempt to update code using the new syntax, from:
QObject::connect(spinBox, SIGNAL(valueChanged(int)), slider, SLOT(setValue(int));
to:
QObject::connect(spinBox, &QSpinBox::valueChanged, slider, &QSlider::setValue);
compiling errors occurred due to unresolved overloaded function issues.
The issue stems from the existence of two overloaded signals named QSpinBox::valueChanged(int) and QSpinBox::valueChanged(QString). Qt provides helper functions to resolve this overloading.
For Qt 5.7 and later:
connect(spinbox, qOverload<int>(&QSpinBox::valueChanged), slider, &QSlider::setValue);
For Qt 5.6 and earlier:
connect(spinbox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), slider, &QSlider::setValue);
This explicit casting, though cumbersome, is necessary to specify the desired signal. It is strongly advised to avoid overloading signals and slots.
C 11 Workaround:
template<typename... Args> struct SELECT { template<typename C, typename R> static constexpr auto OVERLOAD_OF( R (C::*pmf)(Args...) ) -> decltype(pmf) { return pmf; } };
connect(spinbox, SELECT<int>::OVERLOAD_OF(&QSpinBox::valueChanged), ...)
Qt 5.7 Helper Functions:
qOverload<>(&Foo:overloadedFunction) qOverload<int, QString>(&Foo:overloadedFunction)
Consult the Qt documentation for the latest information on handling overloaded signals and slots.
The above is the detailed content of How to Resolve Overloaded Signal-Slot Connections in Qt 5?. For more information, please follow other related articles on the PHP Chinese website!