سؤال

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?

هل كانت مفيدة؟

المحلول

As Jamin and Nikos stated: you should create your own slot to handle the signal emitted by QButtonGroup. It could be something like this:

In the header file:

public slots:

void buttonWasClicked(int);

In the *.cpp file:

void MainWindow::buttonWasClicked(int buttonID)
{
    cout << "You have clicked button: " << buttonID << endl;
}

And in the code responsible for creation of the MainWindow (i.e. in constructor but not necessairly) there should be this line:

    connect(group, SIGNAL(buttonClicked(int)), this, SLOT(buttonWasClicked(int)));

Be aware that since Qt5 the connect syntax has changed. The syntax I used here is from Qt4. It still works but is deprecated now (for more information please refer to New Signal Slot Syntax in Qt 5). Moreover I would suggest going through QButtonGroup class reference as there are other available signals which could suit your needs better than the one I've chosen.

BR

نصائح أخرى

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!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top