是否可以在自动完成弹出列表(Gtk3)中显示图像

Is it possible to display an Image in an autocompletion-popup list (Gtk3)

我正在使用一个 Entry 和一个 EntryCompletion 对象,该对象有一个 ListStore 模型。 对于模型中的每条记录,我想在自动完成弹出列表中显示一张图像。

如何做到这一点? 是否可以向模型添加 Gtk.CellRendererPixbuf 列?

有趣的是,我找不到这方面的任何例子,但事实证明这是可能的,而且并不复杂。让我们从目标的小图像开始,它使用图标是为了令人信服的原因。

那么我们如何到达那里,首先我们创建 ListStore 包含一个列,其中包含要匹配的字符串和一个要转换为 pixbuf 的图标名称(这也可以直接是一个 pixbuf)。

    # Define the entries for the auto complete
    entries = [
        ('revert', 'document-revert'),
        ('delete', 'edit-delete'),
        ('dev help', 'devhelp'),
        ]

    # Setup the list store (Note that the data types should match those of the entries)
    list_store = Gtk.ListStore(str, str)

    # Fill the list store
    for entry_pair in entries:
        list_store.append(entry_pair)

下一步是设置 EntryCompletion 并将其与 Liststore

链接
    # Create the Entry Completion and link it to the list store
    completion = Gtk.EntryCompletion()
    completion.set_model(list_store)

神奇的是,我们需要创建 2 个渲染器,一个用于文本,一个用于 pixbuf。然后我们将这些打包到完成中以向其添加列。

    # Create renderer's for the pixbufs and text
    image_renderer = Gtk.CellRendererPixbuf.new()
    cell_renderer = Gtk.CellRendererText.new()

    # Pack the columns in to the completion, in this case first the image then the string
    completion.pack_start(image_renderer, True)
    completion.pack_start(cell_renderer, True)

为了确保渲染器使用正确的列,我们在此处指定渲染器应读取 ListStore 中的哪一列。对于 image_renderer 我们设置 icon_name 属性,因为我们给它图标名称。如果我们要喂它 Pixbuf,我们将需要 pixbuf

    # Set up the renderer's such that the read the correct column
    completion.add_attribute(image_renderer, "icon_name", 1)
    completion.add_attribute(cell_renderer, "text", 0)

由于没有多列,我们需要告诉补全哪一列包含字符串。在我们的例子中,列 0.

    # Tell the completion which column contains the strings to base the completion on
    completion.props.text_column = 0

    # Create the entry and link it to the completion
    entry = Gtk.Entry()
    entry.set_completion(completion)

就是这样!