Drimer
Drimer

Reputation: 115

How to access dynamically generated QWidgets?

I have a function which generates a QGroupBox with a couple of other elements inside (Buttons, LineEdits, Checkboxes).

def generate_whole_form(self, testbed) -> QGroupBox:

This function is called in a loop, the returned QGroupBox is appended to an array (self.gridArray.append(current_groupbox)) and then put inside a QGridLayout (self.gridlayout.append(current_groupbox)).

I would now like to access the elemets inside the GroupBoxes and I figured there are two ways of doing it:

  1. My generate_whole_form() returns not only the QGroupBox, but also all the other elements I need to deal with later on. Then I could save these handles within the loop.
  2. I could do something like this: self.gridArray[number].findChild(QWidget.QButton, "my_set_objectName") to have access to the single UI elements.

Version 2 seems to be the easier option, as I would not need to manage all the returned UI objects. In fact, I already started implementing it this way, but for some reason, my program breaks, whenever I call findChild(). However, it works fine when I use findChildren().

I would like to know if one of the above mentioned ways is better than the other or if there is even a third way. If version two is preferred, what is going wrong when I use findChild()? How can I use this function correctly?

Upvotes: 0

Views: 157

Answers (1)

eyllanesc
eyllanesc

Reputation: 244142

A simpler solution is to create a QGroupBox where the widgets are owned:

class CustomGroupBox(QGroupBox):
    def __init__(self, params, parent=None):
        super().__init__(parent)
        self._widgets = dict()
 
        for param in params:
            # TODO: create widget using param
            widget = QWidget() 
            # TODO: add layout
            self.widgets[custom_key] = widget

    @property
    def widgets(self):
        return self._widgets

Then:

group_box = CustomGroupBox(...)
print(group_box.widgets)

Upvotes: 1

Related Questions