When attempting to connect overloaded signals and slots using the new pointer-to-member function syntax in Qt 5, some users encounter compilation errors. This article addresses the underlying issue and provides solutions to resolve it.
In the example provided, which implements a connection between a QSpinBox's valueChanged signal and a QSlider's setValue slot, the error stems from the existence of two signals with the same name: valueChanged(int) and valueChanged(QString).
From Qt 5.7 onwards, helper functions have been introduced to assist in resolving signal overloading. These functions allow for specifying the desired overload. In this case, it's possible to use:
connect(spinbox, qOverload<int>(&QSpinBox::valueChanged), slider, &QSlider::setValue);
For earlier versions of Qt, an explicit cast is required to indicate the desired overload:
connect(spinbox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), slider, &QSlider::setValue);
Prior to Qt 5.7, alternative approaches can be employed to cast to the appropriate function pointer:
template<typename... Args> struct SELECT { template<typename C, typename R> static constexpr auto OVERLOAD_OF( R (C::*pmf)(Args...) ) -> decltype(pmf) { return pmf; } };
Usage:
connect(spinbox, SELECT<int>::OVERLOAD_OF(&QSpinBox::valueChanged), ...)
In Qt 5.7, helper functions were added to streamline the process of selecting overloaded signals. The main helper is qOverload (with variations such as qConstOverload and qNonConstOverload).
Example usage (from Qt documentation):
struct Foo { void overloadedFunction(); void overloadedFunction(int, QString); }; // requires C++14 qOverload<>(&Foo:overloadedFunction) qOverload<int, QString>(&Foo:overloadedFunction) // same, with C++11 QOverload<>::of(&Foo:overloadedFunction) QOverload<int, QString>::of(&Foo:overloadedFunction)
In Qt 5.7 onwards, the documentation for overloaded signals now includes guidance on resolving signal overloading issues. For instance, the QSpinBox documentation for valueChanged recommends using the qOverload helper, as shown below:
connect(spinBox, QOverload<const QString &>::of(&QSpinBox::valueChanged), [=](const QString &text){ /* ... */ });
The above is the detailed content of How to Resolve Qt 5 Compilation Errors When Connecting Overloaded Signals and Slots?. For more information, please follow other related articles on the PHP Chinese website!