使用 Qlistview 在 QStandarItemModel 中设置项目的选择

Set selection of item in QStandarItemModel with Qlistview

我有一个 Qlistview 和一些物品。我想在 window 启动时在第一项设置 selection。 selectionModel().selectedRows() returns select 等项目。但 QAbstractItemModel().setCurrentIndex(0) 没有 select 项目。怎么能做到像setSelection(INDEX).

self.listView = QtWidgets.QListView()
self.entry = QtGui.QStandardItemModel()
self.listView.setModel(self.entry) 
----------
self.listView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.listView.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.listView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
----------
self.listView.QAbstractItemModel().setCurrentIndex(0)     #<------ Not really working
selection = self.listView.selectionModel().selectedRows()
print(selection)

如果您想 select 一个项目,那么您必须使用 select() method of selectionModel():

from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.listView = QtWidgets.QListView(
            editTriggers=QtWidgets.QAbstractItemView.NoEditTriggers,
            selectionMode=QtWidgets.QAbstractItemView.SingleSelection,
            selectionBehavior=QtWidgets.QAbstractItemView.SelectRows,
        )
        self.entry = QtGui.QStandardItemModel()
        self.listView.setModel(self.entry)

        for letter in list("abcdefghijklmnopqrstuvwxyz"):
            it = QtGui.QStandardItem(letter)
            self.entry.appendRow(it)

        ix = self.entry.index(0, 0)
        sm = self.listView.selectionModel()
        sm.select(ix, QtCore.QItemSelectionModel.Select)

        self.setCentralWidget(self.listView)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())