Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 808
bobflob Avatar asked Nov 25 '15 14:11

bobflob


2 Answers

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.

like image 156
Elad Joseph Avatar answered Sep 20 '22 22:09

Elad Joseph


selectedIndexes and QModelIndex should be all you need.

liwidg = QtGui.QListWidget()
liwidg.show()
liwidg.setSelectionMode( QtGui.QAbstractItemView.SelectionMode.ExtendedSelection)
liwidg.addItems(["a", "b", "c", "d"])
liwidg.selectedIndexes()

When selected 'a', 'b', and 'c' liwidg.selectedIndexes() Gives:

[<PySide.QtCore.QModelIndex(0,0,0xb266478,QListModel(0xb0e6400) )   at 0x0C86EB20>,
 <PySide.QtCore.QModelIndex(1,0,0xb266518,QListModel(0xb0e6400) )   at 0x0C861D78>,
 <PySide.QtCore.QModelIndex(2,0,0xb2843c8,QListModel(0xb0e6400) )   at 0x0C869AF8>]

You can use the QModelIndex to get whatever information you need.

sel0 = liwidg.selectedIndexes()[0]
# <PySide.QtCore.QModelIndex(0,0,0xb266478,QListModel(0xb0e6400) )   at 0x0C85B530>

print(sel0.data())
print(sel0.row())
print(sel0.column())

Prints:

'a'
0
0

This works for me.

like image 36
justengel Avatar answered Sep 20 '22 22:09

justengel