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

PyGObject(GTK4):如何实现Dropdown随列表变化自动更新?

解决GTK4 Dropdown自动同步列表变化的方案

核心思路是用Gio.ListStore作为可观察的数据容器,配合GTK4的模型绑定机制,让Dropdown自动感知列表变化,同时通过监听选中信号更新当前选中的Coffee实例。

实现步骤

1. 定义可被GTK管理的Coffee类

Coffee需要继承GObject.Object,并将name声明为可观察的GObject属性,让GTK能直接绑定该属性用于显示:

import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Gio', '2.0')
from gi.repository import Gtk, Gio, GObject

class Coffee(GObject.Object):
    __gtype_name__ = 'Coffee'

    name = GObject.Property(type=str)

    def __init__(self, name):
        super().__init__()
        self.name = name

2. 初始化Dropdown与可观察列表

用Gio.ListStore存储Coffee实例,通过Gtk.SingleSelection作为Dropdown的模型,同时设置属性表达式让Dropdown显示Coffee的name字段:

class CoffeeApp(Gtk.Application):
    def __init__(self):
        super().__init__()
        self.coffees = Gio.ListStore.new(Coffee)
        self.curr_coffee = None

    def do_activate(self):
        # 创建SingleSelection管理选中状态
        selection_model = Gtk.SingleSelection(model=self.coffees)
        # 创建Dropdown并绑定模型
        self.dropdown = Gtk.Dropdown(model=selection_model)
        # 设置显示Coffee的name属性
        self.dropdown.set_expression(Gtk.PropertyExpression.new(Coffee, None, 'name'))

        # 监听选中项变化,更新curr_coffee
        self.dropdown.connect('notify::selected-item', self.on_selected_item_changed)

        # 构建窗口
        window = Gtk.ApplicationWindow(application=self, title="Coffee Selector")
        window.set_child(self.dropdown)
        window.present()

    def on_selected_item_changed(self, dropdown, _param):
        self.curr_coffee = dropdown.get_selected_item()
        if self.curr_coffee:
            print(f"Selected: {self.curr_coffee.name}")

3. 同步外部更新的列表

当其他模块需要更新咖啡列表时,直接操作self.coffees这个Gio.ListStore实例即可,增删改操作会自动触发Dropdown的UI更新:

# 示例:添加新咖啡(可在其他模块调用)
def add_coffee(self, name):
    new_coffee = Coffee(name)
    self.coffees.append(new_coffee)

# 示例:删除指定咖啡
def remove_coffee(self, coffee):
    idx = self.coffees.find(coffee)
    if idx != -1:
        self.coffees.remove(idx)

# 示例:清空列表
def clear_coffees(self):
    self.coffees.remove_all()

关键说明

  • Gio.ListStore是GTK推荐的可观察列表容器,任何元素的增删都会自动通知关联的UI组件刷新,无需手动调用刷新方法。
  • Gtk.SingleSelection负责管理选中状态,简化了选中项的监听与获取。
  • 通过set_expression直接绑定Coffee的name属性,无需手动编写cell renderer,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:02:40