I have a QPushButton and when I click the button I will call a method that take two parameters, in this example: exampleMethod(int i, double d)
.
Now I connect the click event from QPushButton button
to the exampleMethod like this:connect(button, &QPushButton::clicked,this, &Example::exampleMethod);
But this doesn't work because the parameter of clicked()
and exampleMethod(int, double)
are not compatible.
Now I created a extra signal: exampleSignal(int i, double d)
to connect to my slot:connect(this, &Example::exampleSignal, this, &Example::exampleMethod);
And a additional slot with no parameters: exampleMethodToCallFromButtonClick()
to call it from QPushButton clicked() in which I call the signal:
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);
}
This works fine.
1) Now my first question: Is this realy the best way to do this without lambda?
With lambda it looks even nicer and I don't need two connect statements:connect(button, &QPushButton::clicked, [this]{exampleMethod(5, 3.6);});
2) My second question: with lamba is this the best way to do this or are there any better ways to solve it?
I also considered to save the parameters from exampleMethod
as a member variable, call the method without parameter and get instead of the parameters the member variables but I think thats not a so good way.
Thanks for your help!
exampleMethodToCallFromButtonClick()
, no need to use signals to callexampleMethod
. You can call the fuction directly without relying on SIGNAL/SLOT – Elcan