Skip to main content
 首页 » 编程设计

python之PySide QSelectionModel.isRowSelected() 函数中的父级是什么

2025年05月04日10freeliver54

我需要确定在 QTableView 中选择了哪些行与 QStandardItemModel 相关联.从 View 中,我调用函数 selectionModel()得到选择。此函数返回 QSelectionModel目的。从那个对象,我想调用 isRowSelected()功能。此函数有两个参数:我要测试的行和一个 parent 参数,它是一个 QModelIndex。 .这就是我迷路的地方。这个 parent 参数有什么用?它从何而来?从概念上讲,我不明白为什么我需要这个参数,具体来说,我不知道我应该将什么值传递给函数以使其工作。

请您参考如下方法:

例如,您会发现 parent 在 QTreeView 中很有用。对于您的用例,这是文档的相关部分:

The index is used by item views, delegates, and selection models to locate an item in the model
...
Invalid indexes are often used as parent indexes when referring to top-level items in a model."

使用 QtCore.QModelIndex() 您将创建一个无效索引,这就是您正在寻找的参数。在此示例中,您可以使用上下文菜单打印行的选择状态:

#!/usr/bin/env python 
#-*- coding:utf-8 -*- 
 
from PyQt4 import QtGui, QtCore 
 
class MyWindow(QtGui.QTableView): 
    def __init__(self, parent=None): 
        super(MyWindow, self).__init__(parent) 
 
        self.modelSource = QtGui.QStandardItemModel(self) 
 
        for rowNumber in range(3): 
            items = [] 
            for columnNumber in range(3): 
                item = QtGui.QStandardItem() 
                item.setText("row: {0} column: {0}".format(rowNumber, columnNumber)) 
 
                items.append(item) 
 
            self.modelSource.appendRow(items) 
 
        self.actionSelectedRows = QtGui.QAction(self) 
        self.actionSelectedRows.setText("Get Selected Rows") 
        self.actionSelectedRows.triggered.connect(self.on_actionSelectedRows_triggered) 
 
        self.contextMenu = QtGui.QMenu(self) 
        self.contextMenu.addAction(self.actionSelectedRows) 
 
        self.setModel(self.modelSource) 
        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 
        self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) 
        self.horizontalHeader().setStretchLastSection(True) 
        self.customContextMenuRequested.connect(self.on_customContextMenuRequested) 
 
    @QtCore.pyqtSlot(bool) 
    def on_actionSelectedRows_triggered(self, state): 
        for rowNumber in range(self.model().rowCount()): 
            info = "Row {0} is ".format(rowNumber) 
            if self.selectionModel().isRowSelected(rowNumber, QtCore.QModelIndex()): 
                info += "selected" 
 
            else: 
                info += "not selected" 
 
            print info 
 
    @QtCore.pyqtSlot(QtCore.QPoint) 
    def on_customContextMenuRequested(self, pos): 
        self.contextMenu.exec_(self.mapToGlobal(pos)) 
 
if __name__ == "__main__": 
    import sys 
 
    app = QtGui.QApplication(sys.argv) 
    app.setApplicationName('MyWindow') 
 
    main = MyWindow() 
    main.resize(333, 222) 
    main.show() 
 
    sys.exit(app.exec_())