get index of selcted item in QListView in python

Viewed 415
self.listOfSongs = QtWidgets.QListView(self.centralwidget)
self.listOfSongs.setGeometry(QtCore.QRect(80, 160, 191, 192))
self.listOfSongs.setObjectName("listOfSongs")
self.model = QtGui.QStandardItemModel()
self.listOfSongs.setModel(self.model)
self.updateList()
def updateList(self):
   self.model.clear()
   for x in self.table:
      item = QtGui.QStandardItem(x)
      self.model.appendRow(item)

I hope someone can tell me how to get the item or the index of the item that I choose by selecting or click on? Using lib pyQT5 in python

enter image description here

1 Answers

QStandardItemModel is a model so you can use all the methods of QAbstractItemModel. You can iterate over rows and use the item() method to get the QStandarItem associated with each index, and then use the text() method of the QStandarItem to get the text.

    self.listOfSongs = QtWidgets.QListView(self.centralwidget)
    self.listOfSongs.setGeometry(QtCore.QRect(80, 160, 191, 192))
    self.listOfSongs.setObjectName("listOfSongs")
    self.model = QtGui.QStandardItemModel()
    self.listOfSongs.setModel(self.model)


    for text in ["Item1", "Item2", "Item3", "Item4"]:
        it = QtGui.QStandardItem(text)
        self.model.appendRow(it)

    self.listOfSongs.clicked[QtCore.QModelIndex].connect(self.on_clicked)

def on_clicked(self, index):
    item = self.model.itemFromIndex(index)
    print (item.text())

on click:

enter image description here

Related