Home > other >  QButtonGroup only contains one button if they are added iteratively
QButtonGroup only contains one button if they are added iteratively

Time:07-21

I'm missing something super simple.. but I've spent 15 minutes on it now, and I don't see it.

This code produces a QButtonGroup with 3 buttons:

from qtpy.QtWidgets import (
    QButtonGroup,
    QPushButton,
    QRadioButton,
    )

buttons = list()
for label in ("Beginner", "Senior", "Expert"):
    cs = QPushButton()
    cs.setObjectName(f"pushButton_{label}")
    cs.setText(label)
    buttons.append(cs)
    
cs_group = QButtonGroup()
for cs in buttons:
    cs_group.addButton(cs)

cs_group.buttons() -> list of 3 elements

This one produces a QButtonGroup with a single button:

from qtpy.QtWidgets import (
    QButtonGroup,
    QPushButton,
    QRadioButton,
    )

cs_group = QButtonGroup()
for label in ("Beginner", "Senior", "Expert"):
    cs = QPushButton()
    cs.setObjectName(f"pushButton_{label}")
    cs.setText(label)
    cs_group.addButton(cs)

cs_group.buttons() -> list with a single element.. the last one.

What am I missing !?

CodePudding user response:

It seems that you do not manage the lifetime of your button instances. So, at the end of the scope of their declaration, they get destructed. They will no longer be valid. This is because the default parent is no parent.

You would need to introduce some parent-child relationship that is typical with Qt. I would probably just parent them to the current widget where you are executing this code.

The same applies to your button group.

  • Related