Home > Backend Development > C++ > How to Resolve Overloaded Signal-Slot Connections in Qt 5?

How to Resolve Overloaded Signal-Slot Connections in Qt 5?

DDD
Release: 2024-12-15 16:19:15
Original
161 people have browsed it

How to Resolve Overloaded Signal-Slot Connections in Qt 5?

Resolving Overloaded Signal-Slot Connections in Qt 5

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.

Encountered Issue

In an attempt to update code using the new syntax, from:

QObject::connect(spinBox, SIGNAL(valueChanged(int)),
                 slider, SLOT(setValue(int));
Copy after login

to:

QObject::connect(spinBox, &QSpinBox::valueChanged,
                 slider, &QSlider::setValue);
Copy after login

compiling errors occurred due to unresolved overloaded function issues.

Overloaded Signal Resolution

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>(&amp;QSpinBox::valueChanged),
        slider, &amp;QSlider::setValue);
Copy after login

For Qt 5.6 and earlier:

connect(spinbox, static_cast<void (QSpinBox::*)(int)>(&amp;QSpinBox::valueChanged),
        slider, &amp;QSlider::setValue);
Copy after login

This explicit casting, though cumbersome, is necessary to specify the desired signal. It is strongly advised to avoid overloading signals and slots.

Alternatives

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;
    } 
};
Copy after login
connect(spinbox, SELECT<int>::OVERLOAD_OF(&amp;QSpinBox::valueChanged), ...)
Copy after login

Qt 5.7 Helper Functions:

qOverload<>(&amp;Foo:overloadedFunction)
qOverload<int, QString>(&amp;Foo:overloadedFunction)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template