Gtk3用另一个部件替换子部件

Gtk3用另一个部件替换子部件

问题描述:

我正在寻找一种从其父部件中移除部件的方法(无论可能是什么 - VBox,网格...)并在其位置添加替代部件。Gtk3用另一个部件替换子部件

我发现this answer,但我似乎无法使它与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 

它不会要么接受容器构件的一个实例。对于我的生活,我无法弄清楚我应该通过什么参数。

P.S .:我知道我可以在容器和子控件之间添加另一个控件,但我不想。

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


感谢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

这是一个如何使用树视图的示例:http://stackoverflow.com/questions/27747172/remove-widget-from-gtk-viewport-scrolled- window-in-dynamic-gui – tobias47n9e 2015-02-20 10:03:45

这个最近才成为可能,因为PyGObject 3.14:https://git.gnome.org/browse/pygobject/commit/?h=pygobject-3-14&id=bf84915f89fd5fd502b4fb162eef7bc0a48c8783

以下任一将工作在PyGObject 3.14及更高版本:

parent.list_child_properties() 
Gtk.ContainerClass.list_child_properties(parent) 

(第二语法的情况下,类和实例方法有一个命名冲突,请参阅讨论here。)

我知道它是如何工作与C,我没跟蟒蛇尝试:

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

PS:在VBox或Grid的情况下,插件不插入到旧插件的位置,您必须指定插入的位置(旧插件的位置)

祝你好运,

你可以试试reparent()方法Gtk.Widget。您可以查看此文档link。如果我记得不错,你应该首先重置子部件,然后移除旧的父部件。如果它在评论中不起作用,我会检查我的文档(目前不在该机器上)。

+0

请不要在这里发布链接。请复制您参考的方法。 – 2014-12-18 10:01:18

+0

Sry,我有点困惑。为什么连接允许,如果它不可取?方法名称是reparent() – cyberbrain 2014-12-18 10:07:48

+0

链接用于获取更多信息。你应该这样做:尝试这种方法:'reparent()'请参阅此链接了解更多信息。 – 2014-12-18 10:08:51