[英]Overriding text() in PySide QtGui.QStandardItem
I have a class overriding the text() method of QtGui.QStandardItem : 我有一个类重写QtGui.QStandardItem的text()方法:
class SourceFileItem(QtGui.QStandardItem):
def __init__(self, name):
super(SourceFileItem, self).__init__("Original Name")
def text(self):
return "Name from Override"
But when I add this to a QStandardItemModel and set that as the model for a listView only the text from the call to the parent class' init method is displayed and there's no evidence of my overridden method being called at all. 但是,当我将其添加到QStandardItemModel并将其设置为listView的模型时,仅显示对父类的init方法的调用中的文本,并且根本没有证据表明我的重写方法被调用了。
The documentation seems to indicate this is the right method for returning the display text: 文档似乎表明这是返回显示文本的正确方法:
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.
This won't work, because QStandardItem.text
isn't a virtual function. 这将不起作用,因为QStandardItem.text
不是虚拟函数。
As you've already discovered, overriding a non-virtual function is mostly useless, because although it will work fine on the Python side, it won't be visible on the C++ side, and so it will never be called internally by Qt. 正如您已经发现的那样,重写非虚拟函数几乎没有用,因为尽管它在Python方面可以正常工作,但在C ++方面却不可见,因此Qt永远不会在内部对其进行调用。
However, in this particular case, all is not lost, because the text()
function is roughly equivalent to this: 但是,在这种特殊情况下,所有内容都不会丢失,因为text()
函数大致等效于此:
def text(self):
return self.data(QtCore.Qt.DisplayRole)
and QStandardItem.data
is virtual. 和QStandardItem.data
是虚拟的。
So all you need is something like this: 因此,您需要的是这样的东西:
def data(self, role=QtCore.Qt.UserRole + 1):
if role == QtCore.Qt.DisplayRole:
return 'Name from Override'
return super(SourceFileItem, self).data(role)
and now your overidden data()
function will be called by Qt from within its text()
function. 现在Qt将从其text()
函数中调用您覆盖的data()
text()
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.