Question

I am so confused on how this whole thing works.

I have some pushbuttons that I put into a group like this:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    AddSlotsToGroup();
}

void MainWindow::AddSlotsToGroup()
{
    QButtonGroup* group = new QButtonGroup(this);
    group->addButton(ui->slot_0);
    group->addButton(ui->slot_1);
    //...
}

And I want to create a slot that gets the id of the button that was clicked in that group. (Sorry if I explained that poorly :( )

So this is what I did (pure guess after googling)

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    AddSlotsToGroup();
    connect(QPushButton* group, SIGNAL(buttonClicked(int)), this, SLOT(onGroupButtonClicked(int)));
}

void MainWindow::onGroupButtonClicked(int id)
{
    qDebug() << id;
}

And to no surprise, I got an error saying group is an undeclared identifier and that QPushButton was an illegal use etc.

I hate to say that I have only used signals/slots from the designer window, so I really just need this one thing, and then I'm set for the future. :)

Thanks for your time. :)

Was it helpful?

Solution

Try the following:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    AddSlotsToGroup();
}

void MainWindow::AddSlotsToGroup()
{
    QButtonGroup* group = new QButtonGroup(this);
    group->addButton(ui->slot_0);
    group->addButton(ui->slot_1);
    //...
    connect(group, SIGNAL(buttonClicked(int)),
            this, SLOT(onGroupButtonClicked(int)));
}

By the way, you need to learn C++ first to master Qt.

OTHER TIPS

First you need to include QButtonGroup.

#include <QButtonGroup>

Your connection is malformed, please save "group" pointer as class member first and then use following:

connect(group, SIGNAL(buttonClicked(int)), this, SLOT(onGroupButtonClicked(int)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top