如何设置Gtk Stack中项目的位置?Python+PyGObject下插入页面
在PyGObject的Gtk Stack中插入页面到指定位置
Gtk Stack没有提供像Gtk.ListBox那样直接按索引插入的方法,但可以通过insert_child_after()或insert_child_before()这两个API实现精准插入到指定页面的前后位置,这就是最简便的解决方案。
具体实现步骤
假设你已经向Stack中添加了Welcome和Editor页面,现在要在两者之间插入Settings页面:
- 获取参考页面的对象:你可以直接使用创建页面时保存的对象,或者通过页面名称用
get_child_by_name()方法获取。 - 调用插入方法:使用
insert_child_after()将新页面插入到参考页面之后,或者用insert_child_before()插入到目标页面之前,两种方式都能实现插入到Welcome和Editor中间的效果。
完整代码示例
import gi gi.require_version('Gtk', '4.0') from gi.repository import Gtk class StackDemo(Gtk.ApplicationWindow): def __init__(self, **kwargs): super().__init__(**kwargs, title="Stack Insert Demo") self.set_default_size(300, 200) # 创建Stack控件 self.stack = Gtk.Stack() self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT) # 添加初始页面 welcome_page = Gtk.Label(label="Welcome Page") self.stack.add_named(welcome_page, "welcome") editor_page = Gtk.Label(label="Editor Page") self.stack.add_named(editor_page, "editor") # 创建要插入的Settings页面 settings_page = Gtk.Label(label="Settings Page") # 方式1:直接用已保存的页面对象插入到Welcome之后 self.stack.insert_child_after(settings_page, welcome_page) # 方式2:通过页面名称获取参考对象后插入(适合页面对象未保存的场景) # welcome_child = self.stack.get_child_by_name("welcome") # if welcome_child: # self.stack.insert_child_after(settings_page, welcome_child) # 添加Stack切换按钮 stack_switcher = Gtk.StackSwitcher(stack=self.stack) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) box.append(stack_switcher) box.append(self.stack) self.set_child(box) app = Gtk.Application(application_id="org.example.StackDemo") app.connect("activate", lambda app: StackDemo(application=app).present()) app.run(None)
关键API说明
insert_child_after(stack, child, sibling):将child插入到sibling页面的后面insert_child_before(stack, child, sibling):将child插入到sibling页面的前面get_child_by_name(stack, name):通过页面的名称(添加时指定的第二个参数)获取对应的页面对象,返回None表示未找到
内容的提问来源于stack exchange,提问作者ShadowOfHassen
相关产品推荐
相关产品推荐

