0

I'm trying to connect a QButtonGroup to a function. But I just can't get it working.

What my code looks like for now:
mainwindow.h:

public slots:
    void UserButtonGroup_idClicked(int id);

mainwindow.cpp:

void MainWindow::UserButtonGroup_idClicked(int id) {
    ui->label->setText("Button #" + QString::number(id) + " was clicked!");
}

void MainWindow::refresh_user_buttons() {
    QButtonGroup UserButtonGroup(this);

    for(int i = 0; i<20; ++i){
        QPushButton* newButton = new QPushButton("Button " + QString::number(i));
        newButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
        ui->vl_users->addWidget(newButton);
        UserButtonGroup.addButton(newButton, i);
    }
    connect(&UserButtonGroup, &QButtonGroup::idClicked, this, &MainWindow::UserButtonGroup_idClicked);
}

I already tried (except from this above):
2.

connect(&UserButtonGroup, SIGNAL(idClicked(int)), this, SLOT(UserButtonGroup_idClicked(int));
  1. Using the slot name: on_UserButtonGroup_idClicked(int id)
    to auto-connect by name.

But it just won't work. When trying method 1 and 2 I won't get any error or issue, but the buttons just won't do anything. When trying to connect slots by name it gives the error "No matching signal for on_UserButtonGroup_idClicked(int)".

I hope you can help me with this one, since I'm running out of ideas.

DomeE__
  • 21
  • 3
  • did you use Q_OBJECT macro? – Patrick Parker Feb 08 '21 at 09:37
  • @PatrickParker Yes Q_OBJECT is used in mainwindow.h if you mean this. Edit: I tried to remove it and I would get an error if it wasn't present. – DomeE__ Feb 08 '21 at 09:41
  • 2
    Your `QButtonGroup` is scoped locally with the `MainWindow` ctor. As soon as it goes out of scope its destructor is called and the connection will be removed. Try making the `QButtonGroup` a member of `MainWindow`. – G.M. Feb 08 '21 at 09:48
  • @G.M. Oh man. I feel stupid now. It works! Such a simple fix. Thank you very much! – DomeE__ Feb 08 '21 at 09:53

0 Answers0