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

时间:2019-07-05 09:57:52

标签: python pyqt pyqt5 qlistview qstandarditemmodel

我有一个Qlistview,上面有一些物品。我想在窗口启动时在第一项设置选择。 selectionModel().selectedRows()返回selectet项。但 QAbstractItemModel().setCurrentIndex(0)未选择该项。怎么能像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)

1 个答案:

答案 0 :(得分:2)

如果要选择一个项目,则必须使用select()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_())