这是在Qt信号和插槽中使用参数调用函数的好方法吗?

Is this a good way to call function with parameter in Qt signal and slot

本文关键字:函数 调用 参数 方法 Qt 信号 插槽      更新时间:2023-10-16

我有一个QPushButton,当我单击该按钮时,我将调用一个采用两个参数的方法,在本例中为:exampleMethod(int i, double d)

现在我将 QPushButtonbutton中的点击事件连接到示例方法如下:
connect(button, &QPushButton::clicked,this, &Example::exampleMethod);

但这不起作用,因为clicked()exampleMethod(int, double)的参数不兼容。

现在我创建了一个额外的信号:exampleSignal(int i, double d)连接到我的插槽:
connect(this, &Example::exampleSignal, this, &Example::exampleMethod);

还有一个没有参数的附加插槽:exampleMethodToCallFromButtonClick()从 QPushButton clicked() 调用它,我在其中调用信号:

Example::Example(QWidget *parent) : QWidget(parent){
button = new QPushButton("Click", this);
connect(button, &QPushButton::clicked,this, &Example::exampleMethodToCallFromButtonClick);
connect(this, &Example::exampleSignal, this, &Example::exampleMethod);
}
void Example::exampleMethod(int i, double d){
qDebug() << "ExampleMethod: " << i << " / " << d;
}
void Example::exampleMethodToCallFromButtonClick(){
emit exampleSignal(5,3.6);
}

这工作正常。

1)现在我的第一个问题:这是没有lambda的最佳方法吗?

使用 lambda,它看起来更好,我不需要两个连接语句:
connect(button, &QPushButton::clicked, [this]{exampleMethod(5, 3.6);});

2)我的第二个问题:对于lamba,这是最好的方法还是有更好的方法来解决它?

我还考虑将exampleMethod中的参数保存为成员变量,调用不带参数的方法并获取成员变量而不是参数,但我认为这不是一个好方法。

感谢您的帮助!

我不会做这两件事。接收信号,收集参数,然后调用exampleMethod。当参数在您连接时已知时,lambda 更合适。

Example::Example(QWidget *parent) : QWidget(parent){
button = new QPushButton("Click", this);
connect(button, &QPushButton::clicked, this, &Example::onButtonClicked);
}
void Example::exampleMethod(int i, double d){
qDebug() << "ExampleMethod: " << i << " / " << d;
}
void Example::onButtonClicked(){
int i = ...;
double d = ...;
exampleMethod(i, d);
}

除了另一个答案中的单一方法方法之外,也许id的值是不相关的,将它们分解为自己的方法是有意义的:

int Example::iValue() const {
...
}
double Example::dValue() const {
...
}

然后,以下内容是等效的:

connect(..., this, [this]{ exampleMethod(iValue(), dValue()); });
connect(..., this, std::bind(&Example::exampleMethod, this, iValue(), dValue()));

onButtonClicked()iValue()dValue()的使用之间的选择主要取决于这些值在单独分解时是否有用,以及对于代码理解,在connect站点指定调用或将其移动到单个方法是否有意义。

最后,如果您确实使用单方法方法,并且按钮是使用setupUi实例化的,即您已在设计器中设计了Example,则可以通过适当命名处理程序方法来保存connect调用:

Q_SLOT void Example::on_button_clicked();

此处button是 .ui 文件中按钮对象的名称。连接将由Ui::Example::setupUi(QWidget*)自动建立。