Passing another variable to a SLOT in QObject::connect
Suppose there are two widgets, a QPushButton and a QLabel
How can I write the connecting code, so that when the button is pressed down, a specific string is displayed in the Label?
shows an error…
If I put:
where would the value for the string come from?
…I am just starting to learn using Qt…
14 replies
Both statements are invalid.
In short:
- connect() wants only the SIGNATURE of the signal/slot (without the return type), not the argument names, nor anything else;
- a slot cannot have more arguments than the ones carried by the signal you’re connecting to it (where should they come from?);
- passing values inside connect() is an error, although it’s pretty clear what you’d like to do;
- simply use a “proxy” slot that calls the target slot with the arguments, or read the docs about QSignalMapper.
In your (very simple) case, if it’s applicable, you can just provide a default argument for the slot. Otherwise, simply create another slot that calls the setText one with the string you want.Indeed. With a slot called setText(), providing a default argument can be misleading:
- myLabel->setText();
What does that do?
Oh well. It’s a style issue.
QSignalMapper [doc.qt.nokia.com] might also be an option.
to solve simple problem like yours I use this solution:
- connect(button1, SIGNAL(clicked()), SLOT(buttonClicked());
- connect(button2, SIGNAL(clicked()), SLOT(buttonClicked());
- button1->setProperty("name", "button1");
- button2->setProperty("name", "button2");
- ...
- ...
- MyClass::buttonClicked()
- {
- if(button->property("name").toString() == "button1")
- {
- .....
- .....
- }
- else if(button->property("name").toString() == "button2")
- {
- ....
- ....
- }
- }
Luca, that is unsave code.
You don’t know what kind of object sender() refers to, or if it is non-0 at all (direct call to buttonClicked()). So, you should at least check that before assuming this. Using a QSignalMapper is the safe way to go, and it still allows other ways to trigger the slot and still work correctly.
Luca, that is unsave code.You don’t know what kind of object sender() refers to, or if it is non-0 at all (direct call to buttonClicked()). So, you should at least check that before assuming this. Using a QSignalMapper is the safe way to go, and it still allows other ways to trigger the slot and still work correctly.
Yes, I usually check if pointer is a push button with a dynamic_cast:
- if(button==NULL)
- {
- return;
- }
Mine is only a fast example…
Hi there is a tool which do exactly what you need.
See QSignalMapper [doc.trolltech.com]
There is good example how to use it.
You must log in to post a reply. Not a member yet? Register here!





