views:

860

answers:

3

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?

A: 

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.

Dmitri
Apparently button(2) was wrong, buttons()[2] was needed instead. Can't say more since I almost never use Qt.
Blindy
+1  A: 

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.

xgoan
Yes, I now use operator[] for both QList and QButtonGroup.Thanks!
Dmitri
Be careful using the operator[] you can do mistakes and have unwanted behaviour.
xgoan
+3  A: 

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.

TimW