Question

I am writing an application in Python 2.7 using PyGTK 2. Basically I create TreeView widget, fill it with content and then check if the selection is changed. When it is true I want the selection to be printed in TextView box. My idea is to get selected value, update text and refresh widget. Here is how i get the selected value:

Definition:

class SomeClass:
    def __init__(self):
        ...
        someTextView = build_textview("some text")
        ...
        tree_selection = someTreeView.get_child().get_selection()
        tree_selection.connect("changed", self.selection_changed())
        ...

    # Signal handler: 
    def selection_changed(self, widget, data=None):
        (model, pathlist) = widget.get_selected_rows()
        for path in pathlist :
            tree_iter = model.get_iter(path)
            value = model.get_value(tree_iter,0)
            return value

As you see, selection_changed handler returns value. The question is how can I save that value after handler is called? I know that I can use a global variable or class attribute but it is not an option. I would like the code to look neat. i.e. like that:

tree_selection.connect("changed", value=self.selection_changed())

but of course it doesn't work.

Was it helpful?

Solution

It doesn't make sense for a signal handler to return the value, return it where?

The signal handler should be a method of a class where it makes sense to store the value as an attribute, ie:

class SomeClass:
    def __init__(self):
        self.value = None
        ...
        someTextView = build_textview("some text")
        ...
        tree_selection = someTreeView.get_child().get_selection()
        tree_selection.connect("changed", self.selection_changed)
        ...

    def selection_changed(self, widget, data=None):
        (model, pathlist) = widget.get_selected_rows()
        for path in pathlist :
            tree_iter = model.get_iter(path)
            value = model.get_value(tree_iter,0)
            this.value = value
            return

Notes:

  • __init__ method declares value attribute
  • in connect method change self.selection_changed() for self.selection_changed so you pass the method itself and not the method's result.
  • selection_changed method stores the value in the attribute and returns nothing.

Hope it helps.

Update

If you still feel your code will look nicer if it explicitly shows where it's storing the value, you could do something like this:

def __init__(self):
    self.value = None
    ...
    someTextView = build_textview("some text")
    ...
    def selection_changed_handler(widget, data):
        value = self.selection_changed(widget, data)

    tree_selection = someTreeView.get_child().get_selection()
    tree_selection.connect("changed", selection_changed_handler)
    ...

But I think the first one is the standard approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top