我有这个代码:
QObject::connect(lineEdit_1, SIGNAL(textChanged(const QString &)), MainWindow, SLOT(myMethod(const QString &, QLineEdit* )) );
Run Code Online (Sandbox Code Playgroud)
当myMethod只有第一个参数(等于SIGNAL)时,此代码可以正常工作,但我需要传递一个指针lo lineEdit_1,以便myMethod知道它必须在哪个LineEdit上运行.我该怎么办?
非常感谢.
您没有必要作为附加参数发送为其发出信号的对象,QObjects具有sender()允许我们获取该对象的方法:
QObject::connect(lineEdit_1, &QLineEdit::textChanged, MainWindow, &Your_Class::myMethod);
Run Code Online (Sandbox Code Playgroud)
void Your_Class::MyMethod(const QString & text){
    if(QLineEdit *le = qobject_cast<QLineEdit *>(sender())){
        qDebug() << le;
    }
}
Run Code Online (Sandbox Code Playgroud)
如果需要传递其他参数,可以使用lambda函数,但总是花时间查看限制(如何使用它取决于上下文):
QObject::connect(lineEdit_1, &QLineEdit::textChanged, [ /* & or = */](const QString & text){
    MainWindow->MyMethod(text, another_arguments);
});
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           203 次  |  
        
|   最近记录:  |