python-3.x - 漏洞?在 PyQt5 中为 QStandardItemModel 实现 rowCount() 有奇怪的效果
问题描述
我只是想实现反对QStandardItemModel
并试图rowCount()
返回 |rows| + 1 显示额外的一行。我会实施data()
并flags()
相应地显示额外行的有效值。
但现在我很困惑。额外的线被绘制(因此该方法被正确实现),但data()
将flags()
始终使用内部数据模型内的索引调用。此外,我的应用在大约 50% 的情况下会崩溃。
所以它看起来并不适用于应该rowCount()
使用它的所有情况,这会导致对内部数据的无效访问..
这是一个错误吗?
我在 Linux (Ubuntu 18.04) 上使用 PyQt5-5.14.0
from PyQt5 import QtWidgets, QtGui, QtCore
class MyModel(QtGui.QStandardItemModel):
def __init__(self):
super().__init__()
self.appendRow([QtGui.QStandardItem("Hi"), QtGui.QStandardItem("there")])
self.appendRow([QtGui.QStandardItem("Hello"), QtGui.QStandardItem("world")])
def rowCount(self, parent):
return super().rowCount() + 1
def data(self, index: QtCore.QModelIndex, role: QtCore.Qt.ItemDataRole):
assert index.row() < 2 # index.row() is always in [-1, 0, 1]
return super().data(index, role)
def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlags:
assert index.row() < 2 # index.row() is always in [-1, 0, 1]
return super().flags(index)
class Testing(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
model = MyModel()
view = QtWidgets.QTableView(self)
view.setModel(model)
self.setCentralWidget(view)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
test = Testing()
raise SystemExit(app.exec_())
解决方案
我忘了实施index()
:
def index(self, row, column, parent):
return super().index(row, column) if row < super().rowCount() else self.createIndex(row, column)
解释:super().index()
将为行创建无效索引 > |内部数据| 这导致flags()
或data()
根本不被调用。
推荐阅读
- reactjs - 在没有 ServiceWorker 的情况下使用 Create React App
- javascript - FlickityCall - 以编程方式上一个/下一个事件
- node.js - 为什么 Cors 阻止我对我的 Api 的请求?
- angular - 为什么在此示例中我无法访问在另一个组件(不是子组件)中定义的 div 的 @ViewChild 引用?
- version-control - 使用 p4 zip 和 unzip 将文件从一个 perforce 服务器导出到另一个
- micropython - WLAN 问题:进入函数体后 WLAN 自动连接
- c - 在 Fortran C 绑定中包装指针到指针
- .net-core - .NET Core 单一发布文件的混淆器
- matrix - 不同大小的矩阵相乘
- tensorflow2.0 - 解释 Tensorboard (TF 2) 中的“空闲时间”