6

How should I proceed if I want to get an especific widget from a layout in python Qt?

What I have done so far:

for i in range(self.ui.horizontalLayout_14.count()): 
    #here it does fail
    name = self.ui.horizontalLayout_14.itemAt(i).objectName()

    #if the above would had worked, then I could do something like this for example
    if "button" in name:
        self.ui.horizontalLayout_14.itemAt(i).widget().close()

Note that, for the example, I am using button but It might be whatever widget inside the layout, lineEdit, or comboBox, labels, etc etc, but not all of them though.

codeKiller
  • 5,493
  • 17
  • 60
  • 115

1 Answers1

19

The problem is that itemAt() function returns the QLayoutItem and not a widget. So you have to call the QLayoutItem::widget() function to get the containing widget, i.e.:

name = self.ui.horizontalLayout_14.itemAt(i).widget().objectName()

UPDATE

However, you can do the same much easier with using the QObject::findChild() function. I.e.:

widget = self.ui.findChild(QPushButton, "button")
# Check whether the returned widget is null...
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • yes you were right, it works now, thanks!. The update looks fine for me as well. Great. I will accept this as an answer as soon as it lets me – codeKiller Dec 01 '14 at 09:51