【问题标题】:Set style property in PyGObject在 PyGObject 中设置样式属性
【发布时间】:2025-11-25 08:55:01
【问题描述】:

我有一个非常简单的 PyGObject 应用程序:

from gi.repository import Gtk, Gdk


class Window(Gtk.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_border_width(5)

        self.progress = Gtk.ProgressBar()
        self.progress.set_fraction(0.5)

        self.box = Gtk.Box()
        self.box.pack_start(self.progress, True, True, 0)

        self.add(self.box)
        self.connect('delete-event', Gtk.main_quit)
        self.show_all()


win = Window()
Gtk.main()

我想让进度条变粗。所以我发现有一个样式属性:

Name                        Type    Default  Flags  Short Description
min-horizontal-bar-height   int     6        r/w    Minimum horizontal height of the progress bar

但是,我似乎无法以我尝试的任何方式设置样式属性。

1) 我尝试使用 CSS:

style_provider = Gtk.CssProvider()

css = b"""
GtkProgressBar {
    border-color: #000;
    min-horizontal-bar-height: 10;
}
"""

style_provider.load_from_data(css)

Gtk.StyleContext.add_provider_for_screen(
    Gdk.Screen.get_default(),
    style_provider,
    Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)

但我得到了一个错误:

GLib.Error: gtk-css-provider-error-quark: <data>:4:37'min-horizontal-bar-height' is not a valid property name (3)

2) 我尝试了set_style_property 方法和this answer to similar question 中描述的所有方法。

一)

self.progress.set_property('min-horizontal-bar-height', 10)

TypeError: object of type 'GtkProgressBar' does not have property 'min-horizontal-bar-height'

b)

self.progress.set_style_property('min-horizontal-bar-height', 10)

AttributeError: 'ProgressBar' object has no attribute 'set_style_property'

c)

self.progress.min_horizontal_bar_height = 10

GLib.Error: gtk-css-provider-error-quark: <data>:4:37'min-horizontal-bar-height' is not a valid property name (3)

d)

self.progress.props.min_horizontal_bar_height = 10

AttributeError: 'gi._gobject.GProps' object has no attribute 'min_horizontal_bar_height'

e)

self.progress.set_min_horizontal_bar_height(10)

AttributeError: 'ProgressBar' object has no attribute 'set_min_horizontal_bar_height'

知道如何让进度条变粗吗?

【问题讨论】:

    标签: python gtk3 pygobject


    【解决方案1】:

    在 CSS 中,您必须在样式属性的名称前面加上一个破折号以及该样式属性所属的类的名称:

    GtkProgressBar {
        -GtkProgressBar-min-horizontal-bar-height: 10px;
    }
    

    它们不打算在代码中设置,因此style_get_property()没有对应的setter方法。

    【讨论】:

    • 太棒了!是否有很好的文档以及如何在 GTK 中使用 CSS 进行样式设置?例如,运行时中的单独小部件、整个应用程序的样式等?我很难找到任何相关的东西。
    • Here's the documentation for styling with GTK CSS。它可能会更好,但它是对您可以做什么的相当不错的概述。
    • 对不起,什么?这个“带有类名和破折号的前缀”真的记录在哪里?无论如何,不​​在链接页面中。
    • 这是一种非常激进的说法。您是否认为我故意将人们指向错误的页面?不,他们在最新版本中重新组织了 CSS 文档。 Here's the page I originally linked to.它在“描述”部分的底部。
    最近更新 更多