Selecting Overloaded Signals and Slots
With the string-based syntax, parameter types are explicitly specified. As a result, the desired instance of an overloaded signal or slot is unambiguous.
In contrast, with the functor-based syntax, an overloaded signal or slot must be casted to tell the compiler which instance to use.
For example, QLCDNumber has three versions of the display() slot:
QLCDNumber::display(int)
QLCDNumber::display(double)
QLCDNumber::display(QString)
To connect the int version to QSlider::valueChanged(), the two syntaxes are:
auto slider = new QSlider(this);
auto lcd = new QLCDNumber(this);
// String-based syntax
connect(slider, SIGNAL(valueChanged(int)),
lcd, SLOT(display(int)));
// Functor-based syntax, first alternative
connect(slider, &QSlider::valueChanged,
lcd, static_cast<void (QLCDNumber::*)(int)>(&QLCDNumber::display));
// Functor-based syntax, second alternative
void (QLCDNumber::*mySlot)(int) = &QLCDNumber::display;
connect(slider, &QSlider::valueChanged,
lcd, mySlot);
// Functor-based syntax, third alternative
connect(slider, &QSlider::valueChanged,
lcd, QOverload<int>::of(&QLCDNumber::display));
// Functor-based syntax, fourth alternative (requires C++14)
connect(slider, &QSlider::valueChanged,
lcd, qOverload<int>(&QLCDNumber::display));
Qt连接重载信号与槽的四种方式解析
本文详细介绍了在Qt中使用字符串和函数对象语法连接重载信号和槽的四种方法。通过示例展示了如何明确指定要连接的重载版本,包括使用静态类型转换、成员指针、QOverload和C++14的qOverload。
1723

被折叠的 条评论
为什么被折叠?



