Loop over widgets in PyQt Layout

Just a comment,

items = (layout.itemAt(i) for i in range(layout.count())) 
for w in items:
   doSomething(w)

I tried the first answer but I found that it returns a WidgetItem type, so actually I did a revision:

widgets = (layout.itemAt(i).widget() for i in range(layout.count())) 
for widget in widgets:
   if isinstance(widget, QLineEdit):
        print "linedit: %s  - %s" %(widget.objectName(), widget.text())
   if isinstance(widget, QCheckBox):
        print "checkBox: %s  - %s" %(widget.objectName(), widget.checkState())

This is a very late response but I thought it might be useful for future refence. I was looking for the answer to this question also. But I wanted to identify widget types so I could handle them accordingly. Here is example code of what I found:

for widget in centralwidget.children():
    if isinstance(widget, QLineEdit):
        print "linedit: %s  - %s" %(widget.objectName(),widget.text())

    if isinstance(widget, QCheckBox):
        print "checkBox: %s  - %s" %(widget.objectName(),widget.checkState())

I hope that will be useful for someone someday. :)


You could put the widgets into a generator like so:

items = (layout.itemAt(i) for i in range(layout.count())) 
for w in items:
   doSomething(w)

If you end up using that a lot, you could sock that code into a generator function:

def layout_widgets(layout):
   return (layout.itemAt(i) for i in range(layout.count()))


for w in layout_widgets(layout):
   doSomething(w)

Tags:

Python

Pyqt