How to get a current Item's info from QtGui.QListWidget?
Asked Answered
B

2

12

Created a QtGui.QListWidget list widget:

myListWidget = QtGui.QListWidget()

Populated this ListWidget with QListWidgetItem list items:

for word in ['cat', 'dog', 'bird']:
    list_item = QtGui.QListWidgetItem(word, myListWidget)

Now connect a function on list_item's left click:

def print_info():
    print myListWidget.currentItem().text()


myListWidget.currentItemChanged.connect(print_info)

As you see from my code all I am getting on a left click is a list_item's label name. But aside from a label name I would like to get a list_item's index number (order number as it is displayed in ListWidget). I would like to get as much info on left-clicked list_item as possible. I looked at dir(my_list_item). But I can't anything useful there ( other than already used my_list_item.text() method which returns a list_item's label name). Thanks in advance!

Bigg answered 5/2, 2014 at 0:45 Comment(0)
T
28

Use QListWidget.currentRow to get the index of the current item:

def print_info():
    print myListWidget.currentRow()
    print myListWidget.currentItem().text()

A QListWidgetItem does not know its own index: it's up to the list-widget to manage that.

You should also note that currentItemChanged sends the current and previous items as arguments, so you could simplify to:

def print_info(current, previous):
    print myListWidget.currentRow()
    print current.text()
    print current.isSelected()
    ...
Taynatayra answered 5/2, 2014 at 2:51 Comment(4)
How do use with multiple selections?Codding
@laserpython. QListWidget.selectedItems.Taynatayra
@Taynatayra I meant how do you get the indices of the selectedItems? selectedItems just returns text values, not indices... there is currentRow() but no currentRows()Codding
Please read the docs I linked to. The selectedItems()method returns a list of items, not text. There can only be one current item, so currentRows() makes no sense. To get a QModelIndex from an item, use QListWidget.indexFromItem.Taynatayra
C
2

Well, I have listed some of the things you can display about the current item, if you want more than this then you should look through the PyQt Documentation. link

 def print_info():
    print myListWidget.currentItem().text()
    print myListWidget.row(myListWidget.currentItem())
    print myListWidget.checkState()  # if it is a checkable item
    print myListWidget.currentItem().toolTip().toString()
    print myListWidget.currentItem().whatsThis().toString()

myListWidget.currentItemChanged.connect(print_info)
Crystallo answered 5/2, 2014 at 2:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.