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():
开发者_JS百科
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?
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).
Just to add my 2 cents, as I was looking for this:
itemsTextList = [str(listWidget.item(i).text()) for i in range(listWidget.count())]
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 =)
items = []
for index in xrange(self.listWidget.count()):
items.append(self.listWidget.item(index))
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!
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())
精彩评论