GObject.add_emission_hook只能运行一次

时间:2012-07-07 09:41:27

标签: python gtk gobject

我想使用GObject.add_emission_hook进行连接以捕获类的所有实例的信号。它似乎工作,但只有一次。在下面的最小示例中,“信号接收”仅打印一次,无论其中一个按钮被点击多少次。为什么这样,我怎样才能在每次点击时收到信号?

当然在我的应用程序中,事情更复杂,接收器(这里是Foo类)不知道发出信号的对象。因此,无法连接到物体本身的信号。

from gi.repository import Gtk
from gi.repository import GObject

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Hello World")
        vbox = Gtk.VBox()
        self.add(vbox)
        button = Gtk.Button(label="Click Here")
        vbox.pack_start(button, True, True, 0)
        button = Gtk.Button(label="Or There")
        vbox.pack_start(button, True, True, 0)
        self.show_all()

class Foo:

    def __init__(self):
        GObject.add_emission_hook(Gtk.Button, "clicked", self.on_button_press)

    def on_button_press(self, *args):
        print "signal received"


win = MyWindow()
foo = Foo()
Gtk.main()

1 个答案:

答案 0 :(得分:3)

您应该从事件处理程序返回True,以便在连续事件上触发回调。如果你返回False(当你没有返回任何内容时,我猜测会返回False)然后删除钩子。这可以通过以下示例基于您的示例进行说明:

from gi.repository import Gtk
from gi.repository import GObject

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Hello World")
        vbox = Gtk.VBox()
        self.add(vbox)
        self.connect("destroy", lambda x: Gtk.main_quit())
        button = Gtk.Button(label="Click Here")
        vbox.pack_start(button, True, True, 0)
        button = Gtk.Button(label="Or There")
        vbox.pack_start(button, True, True, 0)
        self.show_all()

class Foo:
    def __init__(self):
        self.hook_id = GObject.add_emission_hook(Gtk.Button, "button-press-event", self.on_button_press)
        GObject.add_emission_hook(Gtk.Button, "button-release-event", self.on_button_rel)

    def on_button_press(self, *args):
        print "Press signal received"
        return False # Hook is removed

    def on_button_rel(self, *args):
        print "Release signal received"
        # This will result in a warning
        GObject.remove_emission_hook(Gtk.Button, "button-press-event",self.hook_id)
        return True


win = MyWindow()
foo = Foo()
Gtk.main()

希望这有帮助!