在 Qt 中,您在 QAbstractItemModel 中有这个例程(以及其他例程)
bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
如果未指定父级,则每次调用时基本上都会实例化一个新的 QModelIndex。
在 python 中,同一行的含义大不相同:每次调用时只会实例化和共享一个 QModelIndex
我不清楚的一点是 PyQt 如何处理这种差异。 documentation似乎是从 C++ 自动生成的,结果默认参数实例化使用相同的语法,但具有完全不同的含义,使问题未得到解决。
这个问题当然会在 PyQt 中对 QAbstractItemModel 进行自定义重新实现。你应该声明
def insertRows(self, row, count, index=QtCore.QModelIndex()):
或
def insertRows(self, row, count, index=None):
如果 index 为 None,则实例化一个新的 QModelIndex?
最佳答案
bool insertRows(int row, int count,
const QModelIndex &parent = QModelIndex());
和
def insertRows(self, row, count, index=QtCore.QModelIndex()):
这两个示例都会导致无效的索引实例。
什么是无效的QModelIndex ?
An invalid model index can be constructed with the QModelIndex constructor. Invalid indexes are often used as parent indexes when referring to top-level items in a model.
是否insertRows每次调用都需要一个新的无效实例吗?
In case of the insertRows function the base class implementation of this function does nothing and returns false.
引用意味着如果您使用QAbstractItemModel
,您需要自己实现insertRows
。
这意味着您需要调用 beginInsertRows它采用父参数。
当涉及到父索引时,Qt 的 C++ 端不会关心给定的是哪个实例。只要它是无效的,就意味着当前项目在模型的顶层并且没有父项。
QAbstractItemModel
不应删除任何不是由它自己创建的索引。
在 C++ 中,父参数作为 const
引用传递,因此不会被 beginInsertRows
函数删除或更改。
我认为,如果 C++ 实例在 Python 中仍被引用时被删除,则可能发生的段错误是您最大的问题。
现在在 Python 中,在函数定义中创建的参数通常有很长的生命周期,可能有一些方法可以删除实例我不知道但通常你应该注意安全。
如果您对此感到担心,只需每次都创建一个新实例即可。
index = index or QtCore.QModelIndex()
但就其值(value)而言,我不记得在函数定义中创建索引实例时遇到过问题,而且我已经多次这样做了。
关于python - pyqt 如何处理默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16957820/