gpt4 book ai didi

python gtk3 treeview 右键没有选择正确的选择

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:46 25 4
gpt4 key购买 nike

我有以下代码,当我直接用右键选择一行时,它输出前一个选择的项目,而不是刚刚点击的当前项目。

我错过了什么?

#!/usr/bin/env python3

from gi.repository import Gtk, GLib, Gio

class Test(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
store = Gtk.ListStore(str)
self.tree = Gtk.TreeView(store)
for i in range(0,10):
store.append(["test " + str(i)])
self.connect("delete-event", Gtk.main_quit)
self.tree.connect("button_press_event", self.mouse_click)

renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Title", renderer, text=0)
self.tree.append_column(column)
self.add(self.tree)

def mouse_click(self, tv, event):
if event.button == 3:
selection = self.tree.get_selection()
(model, iter) = selection.get_selected()
print(model[iter][0])

win = Test()
win.show_all()
Gtk.main()

最佳答案

诀窍是使用 treeview.get_path_at_pos(x, y),使用随按钮按下事件发送的坐标。一旦有了路径,您就拥有了走得更远所需的一切。

这是一个完整的示例,请注意 mouse_click()

中的额外行
#!/usr/bin/env python3

from gi.repository import Gtk, GLib, Gio

class Test(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
store = Gtk.ListStore(str)
self.tree = Gtk.TreeView(store)
for i in range(0,10):
store.append(["test " + str(i)])
self.connect("delete-event", Gtk.main_quit)
self.tree.connect("button_press_event", self.mouse_click)

renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Title", renderer, text=0)
self.tree.append_column(column)
self.add(self.tree)

def mouse_click(self, tv, event):
if event.button == 3:
# Begin added code
pthinfo = self.tree.get_path_at_pos(event.x, event.y)
if pthinfo != None:
path,col,cellx,celly = pthinfo
self.tree.grab_focus()
self.tree.set_cursor(path,col,0)
# End added code

selection = self.tree.get_selection()
(model, iter) = selection.get_selected()
print(model[iter][0])

win = Test()
win.show_all()
Gtk.main()

关于python gtk3 treeview 右键没有选择正确的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28097636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com