You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AdwViewSwitcherBar(Python)仅显示Page1,求可用示例及问题原因

问题修复:AdwViewSwitcherBar 不显示的解决方案

修复后的代码

import gi

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")

from gi.repository import Adw, Gtk


class MainWindow(Adw.ApplicationWindow):
    def __init__(self, app):
        super().__init__(application=app)
        self.set_title("ADW Window with ViewSwitcherBar")
        self.set_default_size(600, 500)

        # 使用 Adw.ToolbarView 管理顶部/底部工具栏,符合 Adwaita 规范的布局方式
        toolbar_view = Adw.ToolbarView()

        # 创建顶部标题栏
        header_bar = Adw.HeaderBar()
        toolbar_view.add_top_bar(header_bar)

        # 创建视图栈
        view_stack = Adw.ViewStack()
        view_stack.add_titled(self._create_page_content("Page 1"), "page1", "Page 1")
        view_stack.add_titled(self._create_page_content("Page 2"), "page2", "Page 2")
        view_stack.add_titled(self._create_page_content("Page 3"), "page3", "Page 3")

        # 创建视图切换器,用于宽窗口时显示在标题栏中
        view_switcher = Adw.ViewSwitcher()
        view_switcher.set_stack(view_stack)
        view_switcher.set_policy(Adw.ViewSwitcherPolicy.WIDE)
        header_bar.set_title_widget(view_switcher)

        # 创建底部切换栏,窄窗口时显示
        switcher_bar = Adw.ViewSwitcherBar()
        switcher_bar.set_stack(view_stack)
        # 强制显示切换栏
        switcher_bar.set_reveal(True)
        # 将切换栏添加到 ToolbarView 底部区域
        toolbar_view.add_bottom_bar(switcher_bar)

        # 设置视图栈为 ToolbarView 的核心内容
        toolbar_view.set_content(view_stack)
        self.set_content(toolbar_view)

    def _create_page_content(self, title):
        """创建页面内容的辅助函数"""
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        box.set_margin_top(20)
        box.set_margin_bottom(20)
        box.set_margin_start(20)
        box.set_margin_end(20)

        label = Gtk.Label(label=title)
        button = Gtk.Button(label="点击我")
        button.connect("clicked", self.on_button_clicked)

        box.append(label)
        box.append(button)

        return box

    def on_button_clicked(self, button):
        print("按钮被点击了!")


class MyApp(Adw.Application):
    def __init__(self):
        super().__init__(application_id="com.example.MyApp")

    def do_activate(self):
        window = MainWindow(self)
        window.present()


if __name__ == "__main__":
    app = MyApp()
    app.run(None)

问题原因说明

  1. 布局组件选型错误:原代码用普通Gtk.Box管理布局,未使用Adwaita推荐的Adw.ToolbarView——该组件专门处理顶部/底部工具栏的自适应显示逻辑,是Adw.ViewSwitcherBar正常工作的基础。
  2. 切换栏默认隐藏:Adw.ViewSwitcherBar的reveal属性默认值为False,即便添加到布局中也不会自动显示,必须手动设置为True。
  3. 宽窗口场景无切换载体:当窗口宽度足够时,Adw.ViewSwitcherBar的切换选项会自动合并到顶部标题栏,但原代码的标题栏未添加对应的Adw.ViewSwitcher组件,导致宽窗口下也看不到切换选项。

内容的提问来源于stack exchange,提问作者jonny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 04:13:12