在init中设置属性时,Setter不会触发

时间:2015-12-04 12:14:38

标签: python

我如何解决这个问题,以便在启动新TreeNode并将属性节点传递给它时触发'setter'事件?

class TreeNode( QtGui.QTreeWidgetItem ):
    def __init__( self, parent, node ):
        super( TreeNode, self ).__init__( parent )
        self._node_object = node

    @property
    def node_object(self):
        return self._node_object

    @node_object.setter
    def node_object(self, value):
        self._node_object = value
        self.setText( 0, self._node_object.name )
        print "set data"

这不会触发setter事件。

node_object = Faction("Doug")
tree_node = TreeNode(self.node_tree, node_object)

然而,这将触发事件......但理想情况下我想直接将节点传递给TreeNode。

node_object = Faction("Doug")
tree_node = TreeNode(self.node_tree, None)
tree_node.node_object = node_object

已更新

这是设置它的正确方法吗?

class TreeNode( QtGui.QTreeWidgetItem ):
    def __init__( self, parent, node ):
        super( TreeNode, self ).__init__( parent )
        self.node_object = node

    @property
    def node_object(self):
        return self._node_object

    @node_object.setter
    def node_object(self, value):
        self._node_object = value
        self.setText( 0, self._node_object.name )
        print "set data"

1 个答案:

答案 0 :(得分:2)

好吧,你通过直接分配给底层属性来绕过setter。如果要调用setter,分配给setter

self.node_object = node