我尝试用Python和GTK3做我的第一个桌面应用程序,但我很快就遇到了问题。 我想显示一个带有URL URL,Title和delete图标的TreeView,但是我在显示和可以单击的图标方面遇到问题,并删除了该行。
我发现that问题,但解决方案对我不起作用。
有什么办法可以做我想要的吗?或者我设计错了?
代码:
# List
self.store = Gtk.ListStore(str, str, str)
self.store.append(['https://www.youtube.com/watch?v=dQw4w9WgXcQ', # URL
'Rick Astley - Never Gonna Give You Up', # Title
'edit-delete']) # Action icon
tree = Gtk.TreeView(self.store)
tree.set_size_request(600, 400)
# Editable URL
url = Gtk.CellRendererText()
url.set_property("editable", True)
url.connect("edited", self.text_edited)
column_url = Gtk.TreeViewColumn("YouTube URL", url, text=0)
column_url.set_min_width(300)
tree.append_column(column_url)
# Title
title = Gtk.CellRendererText()
column_title = Gtk.TreeViewColumn("Title", title, text=1)
tree.append_column(column_title)
# Action icon
action_icon = Gtk.CellRendererPixbuf()
# action_icon.connect("clicked", self.action_icon_clicked)
column_action_icon = Gtk.TreeViewColumn("", action_icon, icon_name=2)
tree.append_column(column_action_icon)
感谢您的帮助
答案 0 :(得分:1)
诀窍是利用Treeview
中的行激活来捕获按钮是否被点击。由于row_activated
会告诉您单击了哪个列和行,以便我们可以删除单击的行。
Treeview
的默认行为是双击激活,但可以使用tree.set_activate_on_single_click(True)
将其更改为单击。现在将听众连接到像tree.connect("row_activated", self.action_icon_clicked)
这样的信号,我们可以使用下面的函数删除点击的行。
def action_icon_clicked(self, treeview, path, column):
# If the column clicked is the action column remove the clicked row
if column is self.column_action_icon:
# Get the iter that points to the clicked row
iter = self.store.get_iter(path)
# Remove it from the ListStore
self.store.remove(iter)
所以完整的代码将成为:
# List
self.store = Gtk.ListStore(str, str, str)
self.store.append(['https://www.youtube.com/watch?v=dQw4w9WgXcQ', # URL
'Rick Astley - Never Gonna Give You Up', # Title
'edit-delete']) # Action icon
tree = Gtk.TreeView(self.store)
tree.set_size_request(600, 400)
# Editable URL
url = Gtk.CellRendererText()
url.set_property("editable", True)
column_url = Gtk.TreeViewColumn("YouTube URL", url, text=0)
column_url.set_min_width(300)
tree.append_column(column_url)
# Title
title = Gtk.CellRendererText()
column_title = Gtk.TreeViewColumn("Title", title, text=1)
tree.append_column(column_title)
# Action icon
action_icon = Gtk.CellRendererPixbuf()
self.column_action_icon = Gtk.TreeViewColumn("", action_icon, icon_name=2)
tree.append_column(self.column_action_icon)
# Make a click activate a row such that we get the row_activated signal when it is clicked
tree.set_activate_on_single_click(True)
# Connect a listener to the row_activated signal to check whether the correct column was clicked
tree.connect("row_activated", self.action_icon_clicked)
def action_icon_clicked(self, treeview, path, column):
# If the column clicked is the action column remove the clicked row
if column is self.column_action_icon:
# Get the iter that points to the clicked row
iter = self.store.get_iter(path)
# Remove it from the ListStore
self.store.remove(iter)