PyQt4: How do you iterate all items in a QListWidget

淺唱寂寞╮ 提交于 2019-12-04 15:43:09

问题


Currently, I use the following while loop in a class that inherits QtGui.QListWidget to iterate all items:

    i = 0
    while i < self.count():
        item = self.item(i)

        i += 1

I was hoping I could use:

for item in self.items():

but the items() method wants a QMimeData object which I don't know how to construct to return all items. Is there a cleaner approach than my while loop above?


回答1:


I don't know what's it with the MIME type either, and I couldn't find a convenience method either. But you could write a simple method like this and be done:

def iterAllItems(self):
    for i in range(self.count()):
        yield self.item(i)

It's even lazy (a generator).




回答2:


Just to add my 2 cents, as I was looking for this:

itemsTextList =  [str(listWidget.item(i).text()) for i in range(listWidget.count())]



回答3:


I know this is old but, I just found out a function findItems(text, Qt.MatchFlags) in QListWidget. So, to iterate all items:

#listWidget is a QListWidget full of items
all_items = listWidget.findItems('', QtCore.Qt.MatchRegExp)
for item in all_items:
  print item

And do whatever you need with the item =)




回答4:


items = []
for index in xrange(self.listWidget.count()):
     items.append(self.listWidget.item(index))



回答5:


Just as a note for others landing here seeking the same information about PyQt5, it's slightly different here.

As user Pythonic stated above for PyQt4, you can still directly index an item using:

item_at_index_n = list_widget.item(n)

But to acquire a list of items for iteration, using an empty string and the MatchRegExp flag doesn't seem to work any more.

One way to do this in PyQt5 is:

all_items = list_widget.findItems('*', PyQt5.Qt.MatchWildcard)

I'm still getting to grips with PyQt, so there may well be an easier / simpler / more elegant way that I simply haven't come across yet. But I hope this helps!




回答6:


items = []
for index in range(self.listWidget.count()):
    items.append(self.listWidget.item(index))

If your wish to get the text of the items

for item in items:
   print(item.text())


来源:https://stackoverflow.com/questions/4629584/pyqt4-how-do-you-iterate-all-items-in-a-qlistwidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!