Dmitri Pisarev
Dmitri Pisarev

Reputation: 1173

Qt: QList of QButtonGroup

Hey! I try to do the following

    QList<QButtonGroup*> groups;
    for (int i=0; i<nGroup; i++)
    {
        QButtonGroup *objects = new QButtonGroup(this);
        objects->setExclusive(false);
        for (int j=0; j<nObject; j++)
        {
            Led *tempLed = new Led();
            tempLed->setAutoExclusive(false);
            layout->addWidget(tempLed,j,i,Qt::AlignLeft);
            objects->addButton(tempLed);
        }
        groups.append(objects);
    }

And then try to do something like this:

groups.at(1)->button(2)->setChecked(true);

The code compiles, but at runtime throws unhandled exception. What am I doing wrong? Any better way to create group of QButtonGroup?

Upvotes: 0

Views: 2280

Answers (3)

TimW
TimW

Reputation: 8447

The QButtonGroup::button function returns the button for a specific ID, but you didn't use an id when you added the button to the buttongroup. QButtonGroup::button returns 0 in your example leading to a null pointer access exception.

...
objects->addButton(tempLed);
...

If you change the code into

...
objects->addButton(tempLed, j );
...

you original code will work.

I prefer QList::at over QList::operator[] because you don't want to change the value (==pointer) in the list.

Upvotes: 3

Jesus Fernandez
Jesus Fernandez

Reputation: 1290

I think the problem is related with the function at. It returns a const item, and you are calling to a non-const function in it.

Use operator[] instead.

Upvotes: 1

Dmitri Pisarev
Dmitri Pisarev

Reputation: 1173

OK, I solved it like this:

QButtonGroup *bG;
bG = groups[gr];
QAbstractButton *aB = bG->buttons()[obj];
aB->setChecked(command);

Didn't really get what was the problem thou.

Upvotes: 0

Related Questions