这是在Qt信号和插槽中使用参数调用函数的好方法吗?
Is this a good way to call function with parameter in Qt signal and slot
我有一个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);
}
除了另一个答案中的单一方法方法之外,也许i
和d
的值是不相关的,将它们分解为自己的方法是有意义的:
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*)
自动建立。
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销