我正在使用以下代码创建QListView和QStandardItemModel:

self.listView = QtWidgets.QListView(self.groupBox2)
self.listView.setGeometry(QtCore.QRect(200, 20, 400, 220))
self.entry = QtGui.QStandardItemModel()


我正在使用类似于以下内容的循环添加项目:

self.item1 = QtGui.QStandardItem("Itemname1")
self.entry.appendRow(self.item1)
self.item2 = QtGui.QStandardItem("Itemname2")
self.entry.appendRow(self.item2)


我如何将这些项目分配给一个列表,知道列表中的0代表“ Itemname1”,1代表“ Itemname2”等?

另外,如何将QListView中的项目设置为选中状态?
setSelected()对于QStandardItemModel似乎不存在

最佳答案

尝试一下:

import sys
from PyQt5       import QtWidgets, QtGui, QtCore
from PyQt5.QtGui import QBrush, QColor

class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        lay = QtWidgets.QVBoxLayout(self)

        self.listView = QtWidgets.QListView()
        self.label    = QtWidgets.QLabel("Please Select item in the QListView")
        lay.addWidget(self.listView)
        lay.addWidget(self.label)

        self.entry = QtGui.QStandardItemModel()
        self.listView.setModel(self.entry)

        self.listView.clicked[QtCore.QModelIndex].connect(self.on_clicked)
        # When you receive the signal, you call QtGui.QStandardItemModel.itemFromIndex()
        # on the given model index to get a pointer to the item

        for text in ["Itemname1", "Itemname2", "Itemname3", "Itemname4"]:
            it = QtGui.QStandardItem(text)
            self.entry.appendRow(it)
        self.itemOld = QtGui.QStandardItem("text")

    def on_clicked(self, index):
        item = self.entry.itemFromIndex(index)
        self.label.setText("on_clicked: itemIndex=`{}`, itemText=`{}`"
                           "".format(item.index().row(), item.text()))
        item.setForeground(QBrush(QColor(255, 0, 0)))
        self.itemOld.setForeground(QBrush(QColor(0, 0, 0)))
        self.itemOld = item

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())


python - PyQt5使用QStandardItemModel获取QListView中的选定索引-LMLPHP

07-28 02:28