gpt4 book ai didi

python - GObject.add_emission_hook 只能工作一次

转载 作者:行者123 更新时间:2023-11-30 23:42:33 25 4
gpt4 key购买 nike

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

最佳答案

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

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

希望这有帮助!

关于python - GObject.add_emission_hook 只能工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11373914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com