简体   繁体   English

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

[英]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? 我如何解决此问题,以便在初始化新的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"

This will not fire the setter event. 这不会触发setter事件。

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传递给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. 好吧,您可以通过直接分配给基础属性来规避setter。 If you want to invoke the setter, assign to the setter : 如果要调用设置器,请分配给设置器

self.node_object = node

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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