Search code examples
pythonqtpyqtqlistwidget

Getting selected rows in QListWidget


I have a Qlistwidget in which I can select multiple items. I can get a list with all the selected items in the listwidget but can not find a way to get a list of the corresponding rows. To get a list of the selected items in the listwidget I used the following code:

print [str(x.text()) for x in self.listWidget.selectedItems()]

To retrieve the rows I am looking for something like:

a = self.listWidget.selectedIndexes()
print a

But this does not work. I have also tried some code which resulted in outputs like this, which is not very useful:

<PyQt4.QtGui.QListWidgetItem object at 0x0000000013048B88>
<PyQt4.QtCore.QModelIndex object at 0x0000000014FBA7B8>

Solution

  • The weird output is because you are getting objects of type QModelIndex or QListWidgetItem. The QModelIndex object has a method to get its row, so you can use:

    [x.row() for x in self.listWidget.selectedIndexes()]
    

    To get a list of all selected indices.