我有这个代码:
QObject::connect(lineEdit_1, SIGNAL(textChanged(const QString &)), MainWindow, SLOT(myMethod(const QString &, QLineEdit* )) );
当 myMethod 只有第一个参数(等于 SIGNAL)但我需要将指针传递给lineEdit_1时,这段代码可以正常工作为了让 myMethod 知道它必须在哪个 LineEdit 上操作。 我该怎么办?
非常感谢。
最佳答案
您不必将为其发出信号的对象 QObject
作为附加参数发送我们有 sender()
允许我们获取该对象的方法:
QObject::connect(lineEdit_1, &QLineEdit::textChanged, MainWindow, &Your_Class::myMethod);
void Your_Class::MyMethod(const QString & text){
if(QLineEdit *le = qobject_cast<QLineEdit *>(sender())){
qDebug() << le;
}
}
如果您需要传递其他参数,您可以使用 lambda 函数,但请务必花时间查看限制(如何使用它取决于上下文):
QObject::connect(lineEdit_1, &QLineEdit::textChanged, [ /* & or = */](const QString & text){
MainWindow->MyMethod(text, another_arguments);
});
关于c++ - QT 用比 SLOT 更少的参数连接 SIGNAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919872/