我有一个类重写 QtGui.QStandardItem 的text()方法:
class SourceFileItem(QtGui.QStandardItem):
def __init__(self, name):
super(SourceFileItem, self).__init__("Original Name")
def text(self):
return "Name from Override"
但是,当我将其添加到 QStandardItemModel 并将其设置为 listView 的模型时,仅显示调用父类'init方法的文本,并且没有证据表明我的被覆盖的方法被调用了。
文档似乎表明这是返回显示文本的正确方法:
PySide.QtGui.QStandardItem.text()
Return type: unicode
Returns the item’s text. This is the text that’s presented to the user in a view.
答案 0 :(得分:1)
这不会奏效,因为QStandardItem.text
不是虚拟功能。
正如您已经发现的那样,覆盖非虚函数几乎是无用的,因为虽然它在Python端可以正常工作,但它在C ++端不可见,所以它会绝不会被Qt内部调用。
但是,在这种特殊情况下,所有内容都不会丢失,因为text()
函数与此大致相同:
def text(self):
return self.data(QtCore.Qt.DisplayRole)
和QStandardItem.data
是虚拟。
所以你需要的就是这样:
def data(self, role=QtCore.Qt.UserRole + 1):
if role == QtCore.Qt.DisplayRole:
return 'Name from Override'
return super(SourceFileItem, self).data(role)
现在,Qt将在其data()
函数中调用您的重叠text()
函数。