1

我想使用 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()
4

1 回答 1

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()

希望这可以帮助!

于 2012-07-07T15:56:14.470 回答