我正在使用Entry
而EntryCompletion
opbject具有ListStore
模型。 對於模型中的每條記錄,我都想在自動完成彈出列表中顯示一幅圖像。是否可以在自動完成彈出列表中顯示圖像(Gtk3)
這怎麼辦? 是否可以將Gtk.CellRendererPixbuf
列添加到模型中?
我正在使用Entry
而EntryCompletion
opbject具有ListStore
模型。 對於模型中的每條記錄,我都想在自動完成彈出列表中顯示一幅圖像。是否可以在自動完成彈出列表中顯示圖像(Gtk3)
這怎麼辦? 是否可以將Gtk.CellRendererPixbuf
列添加到模型中?
有趣的是,我找不到任何這樣的例子,但事實證明這是可能的,而不是瘋狂複雜。讓我們從使用圖標的目標的小圖像開始,以說服原因。
那麼,如何才能到達那裏,我們首先創建一個包含字符串的列來匹配和圖標名稱轉換成pixbuf的(這也可能是直接在這個pixbuf)的ListStore
。
# 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級的渲染器,一個文本,一個用於pixbufs。然後,我們將這些填入完成中以向其添加列。
# 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
's,我們需要改爲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)
就是這樣!
[Here](http://arstechnica.com/information-technology/2009/08/howto-an-introduction-to-gtk-treeviews-and-autocompletion/2/)就是一個例子。 – Marduk
不錯的發現!當我寫這個答案時,我找不到任何例子:) – B8vrede