Solved best way to tune behavior of a QPushButton?
-
Hi, all -
Very basic question here, I'm sure. I'm trying to learn Qt through some of the online examples, and am currently here.
So, the exercise is to enable the two buttons with distinct behavior. I can think of three ways of doing this, but I'm not in love with any of them:
- create subclasses for both buttons. Seems like overkill.
- within the slotButtonClicked() method, examine the return from text() and act accordingly. Seems kind of clunky.
- create a new constructor with an additional parameter to point to the routine to invoke when triggered. Seems unduly complex.
So, are these the choices, or am I unaware of another (hopefully better) way of doing this? I welcome any recommendations.
Thanks.
-
@mzimmers
connect the buttons to specific slotsex. connect
buttonInfo
clicked
signal toapp
aboutQt()
slot and connectbuttonQuit
clicked
signal toapp
quit()
slot -
Here's the example I mentioned:
#include <QApplication> #include <QPushButton> int main(int argc, char **argv) { QApplication app (argc, argv); QWidget window; window.setFixedSize(100, 80); QPushButton *buttonInfo = new QPushButton("Info", &window); buttonInfo->setGeometry(10, 10, 80, 30); QPushButton *buttonQuit = new QPushButton("Quit", &window); buttonQuit->setGeometry(10, 40, 80, 30); window.show(); // Add your code here return app.exec(); }
These buttons aren't defined within the context of an object -- how can I connect them to anything?
-
Hi,
QObject::connect(buttonQuit, &QPushButton::clicked, qApp, &QApplication::quit);
-
Thanks, RGaist. So...is "connect" an actual function, then? I thought it was something for the moc to use.
I assume that you meant "app" where you said "qApp".
I'm not clear on the syntax here: shouldn't the 2nd and 4th arguments be functions, and therefore look like "QPushButton::clicked()"?
Thanks again.
-
@mzimmers Hi! For the signals and slots syntax that was introduced with Qt 5, see this wiki article.
-
connect is a static method of QObject, nothing to do with moc itself.
This example uses this overload that takes point to member function has parameter for the signal and the slot.
No no, I meant qApp which is a pointer to the unique application object created with app. You can replace it with
&app
in this context. -
Wieland: thanks for that link. That new syntax does appear preferable, and is about as intuitive as C++ will let it be.
SGaist: I should have known you wouldn't have an error in one of your responses! Thanks for the explanation.
As an aside, I realize this is just an example, but is it considered good form to program connects outside of an object? I seem to remember reading somewhere that they were intended to be used by and for objects...
-
Don't be so sure, I'm only human and I can make mistakes in my answers :)
Usually you use connect in QObject based classes however it can happen that you need to connect stuff in your main code.