Gtk3如何用一个新的小部件替换子小部件

15

我正在寻找一种方法,可以从一个父小部件中移除另一个小部件(无论它是VBox、Grid还是其他),并在原位置添加一个替代小部件。

我找到了这个答案,但似乎无法在Gtk3中使其工作。

以下是我尝试的内容:

from gi.repository import Gtk

def replace_widget(old, new):
    parent= old.get_parent()

    props= {}
    for key in Gtk.ContainerClass.list_child_properties(type(parent)):
        props[key.name]= parent.child_get_property(old, key.name)

    parent.remove(old)
    parent.add_with_properties(new, **props)

但调用 Gtk.ContainerClass.list_child_properties 会引发异常

TypeError: argument self: Expected a Gtk.ContainerClass, but got gi.repository.Gtk.GObjectMeta

它也不会接受容器小部件的实例。我真的想不出我应该传递哪个参数。

附言:我知道我可以在容器和子小部件之间添加另一个小部件,但我宁愿不这样做。

更新:我想可能不够清楚:替代小部件应该与原始小部件处于相同的位置,并具有相同的打包属性。


这是一个使用树视图的示例:http://stackoverflow.com/questions/27747172/remove-widget-from-gtk-viewport-scrolled-window-in-dynamic-gui - tobias47n9e
4个回答

2

我已经发布了可工作的代码作为答案,但如果您愿意,我们也可以将其添加到您的答案中。 - Aran-Fey
谢谢你的回答,我认为将其作为单独的答案留下来也是可以的。如果你更喜欢合并它们,也可以随意编辑我的答案! - ptomato

2

感谢ptomato的回答提供的信息,以下是可用的代码:

def replace_widget(old, new):
    parent = old.get_parent()

    props = {}
    for key in Gtk.ContainerClass.list_child_properties(type(parent)):
        props[key.name] = parent.child_get_property(old, key.name)

    parent.remove(old)
    parent.add(new)

    for name, value in props.iteritems():
        parent.child_set_property(new, name, value)

0

我知道在C语言中如何工作,但我没有尝试过在Python中:

 parent = gtk_widget_get_parent(old);
 g_object_ref(_key); /** because gtk_container_remove remove the widget with its reference we have to increment the number of reference if we want to reuse the old widget **/
 gtk_container_remove(GTK_CONTAINER(parent), old);
 gtk_container_add(GTK_CONTAINER(parent), new);

提示:如果是在VBox或Grid中,小部件不会插入到旧部件的位置,您需要指定插入位置(即旧部件的位置)

祝好运,


-1
你可以尝试使用 Gtk.Widget 的 reparent() 方法。你可以在 archive.org 中的 gtkwidget/reparent 链接 查看文档。如果我没记错的话,你应该先重新设置子部件的父级,然后再删除旧的父级部件。如果这不起作用,请在评论中留言,我会查看我的文档(目前不在那台机器上,抱歉)。

请不要仅在此处发布链接。请复制您正在引用的方法。 - JSK NS
抱歉,我有点困惑。为什么允许链接,如果它是不可取的呢?方法名是reparent()。 - cyberbrain
链接是提供额外信息的。您应该这样做:尝试使用此方法:reparent(),请参阅此链接以获取更多信息。 - JSK NS
@JSK NS 对不起,感谢您的建议。我会编辑帖子,这些评论可以被删除。 - cyberbrain
这不会在旧小部件的位置添加新小部件。基本上,这就是YouzKing建议的相同内容。 - Aran-Fey
自版本3.14起已弃用:请使用Gtk.Container.remove()和Gtk.Container.add()。 - oxidworks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接