在python的QListView中获取选择项的索引

问题描述 投票:3回答:1
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)

我希望有人可以告诉我如何通过选择或单击来获取我选择的商品或商品的索引?在python中使用lib pyQT5]

enter image description here

python pyqt5 qlistview
1个回答
0
投票

QStandardItemModel是模型,因此您可以使用QAbstractItemModel的所有方法。您可以遍历行,并使用item()方法获取与每个索引关联的QStandarItem,然后使用QStandarItemtext()方法获取文本。

    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())

点击时:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.