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

GTK4中ScrolledWindow导致内容缩小不可读的问题咨询

GTK4 + Python:Gtk.ScrolledWindow包裹Grid后内容被缩小的问题解析与解决

问题原因

核心问题出在布局容器的扩展属性未正确配置:

  • Gtk.ScrolledWindow默认不会主动占据水平方向的可用空间,被放入Gtk.Stack后,Stack会根据子部件的最小尺寸分配空间,直接导致ScrolledWindow被压缩。
  • Gtk.Grid本身未设置水平扩展属性,加上Gtk.Label未开启自动换行,长文本无法自适应宽度,最终内容缩成不可读状态,同时给侧边栏留出了多余空白。

解决方法

只需调整几个部件的扩展属性和文本换行设置,就能让内容区域正常占满空间并保持可滚动特性:

关键调整点

  • 给Gtk.ScrolledWindow设置hexpand=True,让它在水平方向填充Gtk.Stack的剩余空间
  • 给Gtk.Grid设置hexpand=True,确保Grid在ScrolledWindow内水平扩展
  • 给Gtk.Label开启wrap=True,让长文本自动换行,避免横向溢出

修改后的完整代码

#!/usr/bin/python

import sys
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw


class MainWindow(Gtk.ApplicationWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.set_title("Demo")
        self.set_default_size(400, 400)

        # 创建带滚动内容的Grid
        self.grid = Gtk.Grid()
        self.grid.set_hexpand(True)  # 让Grid水平扩展

        for row in range(50):
            label = Gtk.Label(label="Text Text Text Text Text Text Text Text Text")
            label.set_wrap(True)  # 开启文本自动换行
            self.grid.attach(label, 0, row, 1, 1)
 
        # 用ScrolledWindow包裹Grid
        self.scrollableContent = Gtk.ScrolledWindow()
        self.scrollableContent.set_child(self.grid)
        self.scrollableContent.set_hexpand(True)  # 让ScrolledWindow水平占满空间

        # 创建Stack并添加ScrolledWindow
        self.content = Gtk.Stack()
        self.content.add_titled(self.scrollableContent, "Scrollable", "Content . . . . . . . . ")

        # 创建侧边栏
        self.sidebar = Gtk.StackSidebar()
        self.sidebar.set_stack(self.content)

        # 水平布局容器
        self.structure = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        self.structure.set_homogeneous(False)
        self.structure.append(self.sidebar)      
        self.structure.append(self.content)

        self.set_child(self.structure)


class DemoApp(Adw.Application):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.connect('activate', self.on_activate)

    def on_activate(self, app):
        self.win = MainWindow(application=app)
        self.win.present()

app = DemoApp(application_id="com.vildljung.Demo")
app.run(sys.argv)

补充说明

如果不需要文本换行,也可以给Gtk.Label设置hexpand=True,让标签占满Grid的宽度,此时ScrolledWindow会出现横向滚动条。但开启自动换行更符合桌面应用的常规交互逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:34:58