GTK调用小部件的回调函数

时间:2014-02-04 09:38:28

标签: python callback event-handling gtk

我已将回调函数连接到小部件的realize事件。

小部件是树视图,当它实现时,它将从数据库中填充表。 当我从表中打开一个条目时,它会打开一个窗口,我可以在其中编辑数据。 然后我保存数据,窗口关闭,表可能会刷新。

所以我调用treeview.emit('realize')来调用再次填充树视图的函数。 但树视图已损坏,没有列标题,也没有调用回调函数。

我也试过了:

treeview.unrealize()
treeview.realize()

一些代码:

from gi.repository import Gtk
b = Gtk.Builder()
b.add_from_file('file.glade')

def fill_table(treeview, table_name):
    'fills the treeview from database (select * from table_name ...)'
    ...

def open_entry(treeview, row ...):
    'opens the window of the entry'
    w = b.get_object('entry_window')
    ...

def save_and_fill(button):
    'when the SAVE button in the entry_window is clicked, it saves the data, closes the entry_window and fills the treeview'
    #update table1 set column=....
    b.get_object('treeview').emit('realize') #here it might call the fill_table funcion
    b.get_object('entry_window').hide()

signals = {'realize' : lambda *args: fill_table('table1'),
           'row-activated' : open_entry,
           'clicked' : save_and_fill}

b.connect_signals(signals)
b.get_object('main_window').show_all()
Gtk.main()

或仅treeview.realize(),但它不起作用。

调用回调函数是否可以连接到小部件的realize事件而不破坏小部件?

1 个答案:

答案 0 :(得分:1)

你不应该直接发射GtkWidget::realize。在两种情况下,你只能用g_signal_emit()(或语言绑定中的等价)发出信号:

  • 它在安装信号的类中
  • 信号标有G_SIGNAL_ACTION标志

请参阅:https://developer.gnome.org/gobject/stable/gobject-Signals.html#GSignalFlags

另外,你首先滥用了GtkWidget::realize。实现信号应仅用于分配窗口系统资源,如GdkWindow实例,而不是用于构建窗口小部件。如果要填充GtkTreeView使用的模型,可以在特定的回调中执行此操作,也可以在主循环内使用空闲/超时源。