简体   繁体   中英

Setter doesn't fire when setting property inside init

How do i fix this so the 'setter' event fires when i init a new TreeNode and pass it the attribute node?

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"

This will not fire the setter event.

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

However this will fire the event... but ideally i wanted to directly pass the Node to the TreeNode.

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

UPDATED

Is this the proper way of setting it up then?

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"

Well, you're circumventing the setter by directly assigning to the underlying property. If you want to invoke the setter, assign to the setter :

self.node_object = node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM