How to tell when a QPushButton is clicked in a QButtonGroup

mrg95 picture mrg95 · Jul 15, 2013 · Viewed 8.4k times · Source

In my project, I have 40 QPushButtons all put into a QButtonGroup like this:

QButtonGroup* group = new QButtonGroup(this);
group->addButton(ui->slot_0);
group->addButton(ui->slot_1);
//...
group->addButton(ui->slot_38);
group->addButton(ui->slot_39);

Each button is a QPushButton that I made checkable. That way only one button can be checked at a time. All works great, but how can I "make a slot" when one of the buttons becomes checked? I don't want to have 40 different slots, one for each button all to end up doing essentially the same thing. Is there any way I can just use the QButtonGroup I put them in?

Answer

Jamin Grey picture Jamin Grey · Jul 15, 2013

The documentation for QButtonGroup shows a QButtonGroup::buttonClicked() signal - have you already tried that one?

The signal comes in two variants - one that gives the QPushButton as a parameter (as a QAbstractButton), and one that gives the ID of the button in the group.

You can use connect() to setup signal and slot connections in your C++ code.

Sometime during the initialization of your window's class (perhaps in the constructor), call this:

connect(myButtonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(theSlotThatYouWrite(QAbstractButton*));

Where myButtonGroup is probably this->ui->nameOfTheButtonGroup, and theSlotThatYouWrite is a function that you write in your own code, that belongs to your window's class, that returns void and takes a signal QAbstractButton* as a parameter (since that's what this specific signal gives as an argument).

Make sure theSlotThatYouWrite is under the label "private slots:" or "public slots:" in your class's interface.

Here's a screenshot of actual usage of some signals and slots in my own code.

Click to see full size

Signals and Slots is something very important to learn, but can be bit of a hill to climb when first trying to understand it!