我即将调整我的源代码以适应 Qt 中新的信号和槽语法。虽然下面陈述的代码在已弃用的 const char* signal
参数下运行良好,但它不适用于新的 QMetaMethod &signal
语法。
class SignalWaiter : public QObject {
Q_OBJECT
public:
SignalWaiter(const QObject* sender, const QMetaMethod &signal);
private slots:
void signalCaught();
};
SignalWaiter::SignalWaiter(const QObject* sender, const QMetaMethod &signal) {
QObject::connect(sender, signal, this, &SignalWaiter::signalCaught);
}
void SignalWaiter::signalCaught() {
}
编译器在 connect()
命令处停止并显示消息:
error: C2664: 'QMetaObject::Connection QObject::connect(const QObject *,const char *,const char *,Qt::ConnectionType) const': cannot convert argument 2 from 'const QMetaMethod' to 'const char *'
和
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
很明显,编译器试图用旧语法调用重载的 connect 方法。我做错了什么?
最佳答案
connect()
you're trying to use有签名:
QMetaObject::Connection QObject::connect(
const QObject *sender,
const QMetaMethod &signal,
const QObject *receiver,
const QMetaMethod &method,
Qt::ConnectionType type = Qt::AutoConnection)
请注意第 4 个th 参数const QMetaMethod &method
,它不是指向成员的指针,这就是您收到错误的原因。
要进行适当的转换,您可以使用:
auto metaSlot = metaObject()->method(metaObject()->indexOfSlot("signalCaught()"));
QObject::connect(sender, signal, this, metaSlot);
不过,正如@p-a-o-l-o 所指出的,新的信号/槽语法使用指向成员函数的指针,而不是QMetaMethod
。他的解决方案可能正是您真正需要的。
关于c++ - 编译器选择了错误的重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49856646/