mrg95
mrg95

Reputation: 2418

Loop through all buttons in a QButtonGroup

In my project, I have a QButtonGroup with 256 pushbuttons in it. I also gave each button an id like this:

void MainWindow::AddBlocksToGroup()
{
    QButtonGroup* blockGroup = new QButtonGroup(this);
    blockGroup->addButton(ui->Oblock_0, 0);
    ...
    blockGroup->addButton(ui->Oblock_255, 255);
}

I am trying to loop through all the buttons in the group and change their text but I keep getting errors when my program reaches the part where I loop through the buttons. This is what I currently have to loop through them:

for(int i = 0; i <= 255; i++)
{
    blockGroup->button(i)->setText("Test"); //Read access violation?
}

I always get a read access violation in my loop when my program reaches this point. Why is this?

Thanks for your time.

Upvotes: 0

Views: 3310

Answers (3)

Nathan_hnl
Nathan_hnl

Reputation: 33

I know it has been a long time, you probably have already solved this. If not, maybe you need to check whether blockGroup->buttons() return value is an empty list or not. If it is an empty list, then your program crashes.

Upvotes: 0

thuga
thuga

Reputation: 12931

You seem to be creating a local variable called blockGroup in your AddBlocksToGroup() function. Perhaps what you are trying to do is initialize your MainWindow member variable that uses the same name?

So instead of: QButtonGroup* blockGroup = new QButtonGroup(this);

you should do: blockGroup = new QButtonGroup(this);

Upvotes: 0

Chris
Chris

Reputation: 17535

I would do this for the iteration code:

foreach(QAbstractButton *button, blockGroup->buttons()) {
    button->setText("Test");
}

If this still gives you crashes, then there's something else going on in your program that is invalidating those button pointers.

Upvotes: 2

Related Questions