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

如何实现GtkSource.View随系统明暗模式自动切换主题?

解决GtkSource.View跟随系统明暗主题切换的问题

GtkSource.View无法自动跟随系统亮色/深色模式切换,核心原因是它依赖独立的GtkSource.StyleScheme(语法高亮样式方案),这类方案默认不会绑定系统的明暗偏好;而Gtk.TextView直接复用GTK基础主题样式,因此能自动适配。要实现GtkSource.View的自动切换,需手动监听系统主题变化并切换对应样式方案,具体步骤如下:

1. 监听系统明暗模式变化

通过Gtk.Settings的gtk-application-prefer-dark-theme属性变化信号,触发样式切换逻辑。以Python为例:

from gi.repository import Gtk, GtkSource

def sync_gtksource_theme(settings, prop_name, source_view):
    is_dark_mode = settings.get_property(prop_name)
    scheme_manager = GtkSource.StyleSchemeManager.get_default()
    # 切换对应样式方案,这里以Adwaita系列为例
    target_scheme = scheme_manager.get_scheme("Adwaita-dark" if is_dark_mode else "Adwaita")
    source_view.set_style_scheme(target_scheme)

# 绑定信号到你的GtkSource.View实例
gtk_settings = Gtk.Settings.get_default()
gtk_settings.connect("notify::gtk-application-prefer-dark-theme", sync_gtksource_theme, your_source_view)

2. 确认样式方案可用

先检查目标样式方案是否存在,避免找不到方案导致报错。可通过以下代码列出所有可用的样式方案ID:

scheme_manager = GtkSource.StyleSchemeManager.get_default()
for scheme_id in scheme_manager.get_scheme_ids():
    print(scheme_id)

如果需要自定义明暗样式,可将.xml格式的样式文件放到对应版本的GTKSourceView样式目录,比如GTK 4对应的~/.local/share/gtksourceview-5/styles/。

3. 初始化时同步当前主题

程序启动时,需手动同步一次当前系统的明暗状态,避免初始样式和系统主题不匹配:

is_dark_mode = gtk_settings.get_property("gtk-application-prefer-dark-theme")
initial_scheme = scheme_manager.get_scheme("Adwaita-dark" if is_dark_mode else "Adwaita")
your_source_view.set_style_scheme(initial_scheme)

内容的提问来源于stack exchange,提问作者david-swift

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:13:19