我正在尝试使用新语法将信号连接到信号:
connect(ui->line,&QLineEdit::returnPressed,ui->button,&QPushButton::clicked);
但是编译器会抛出一个错误,而旧语法仍然有效:
connect(ui->line,SIGNAL(returnPressed()),ui->button,SIGNAL(clicked()));
我知道这可以连接到功能单击:
connect(ui->line,&QLineEdit::returnPressed,ui->button,&QPushButton::click);
但是有没有办法使用新语法将其连接到信号?
快速浏览一下文档,不匹配源于
clicked
信号的额外参数。
一种选择是使用 lambda 来注入该参数:
connect(ui->line,&QLineEdit::returnPressed, this, [this]() { ui->button->clicked(false); });
为此您需要使用 lambda。但你的例子很好地表明了旧语法的混乱。它会做什么?它发出的信号是 true 还是 false?
我确信它已在某处记录,如果没有其他地方,则在代码中。但肯定的是,使用新的语法,明确地使代码更具可读性,对吗?
所以,如果我是你,我会写这样的东西:
#include <QApplication>
#include <QLineEdit>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLineEdit lineEdit;
QPushButton pushButton;
QObject::connect(&lineEdit, &QLineEdit::returnPressed, [&pushButton]() {emit pushButton.clicked(true);});
return app.exec();
}
对于那些只想知道接收器是否可以成为具有新连接语法的信号的人来说,答案是接收器可以是信号,而不仅仅是插槽。这就是为什么我也更喜欢称之为“新连接语法”而不是“新信号/槽语法”。因此,一个简单的信号到信号“映射”将是这样的:
connect(
sender, &Sender::valueChanged,
receiver, &Receiver::valueChanged,
);