python - 在 Python GTK 中从 ListBox(绑定到 ListStore)中获取选定对象
问题描述
我用 ListBox(作为播放列表)制作了一个简单的 GTK 音乐播放器。
这是 GObject 类,我用来绑定到 ListBox(使用 bind_model() 方法)和 ListStore。
import eyed3
from gi.repository import Gio, GObject
class Song(GObject.GObject):
path = GObject.Property(type=str)
name = GObject.Property(type=str)
def __init__(self, path):
GObject.GObject.__init__(self)
self.path = path
self.file = eyed3.load(path)
self.name = self
def __str__(self):
return str(self.file.tag.artist) + ' - ' + str(self.file.tag.title)
playlist = Gio.ListStore().new(Song)
这就是我将 ListStore 绑定到 ListBox 的方式:
play_listbox.connect('row-selected', self.on_row_selected)
playlist.append(Song('/home/user/Downloads/Some album/01 - Song1.mp3'))
playlist.append(Song('/home/user/Downloads/Some album/02 - Song2.mp3'))
play_listbox.bind_model(playlist, self.create_song_label)
def create_song_label(self, song):
return Gtk.Label(label=song.name)
到目前为止,一切正常。
问题是:是否可以根据选择检索 Song 对象(存储在播放列表中)?要检索存储在该对象中的路径属性?
如果没有,是否有可能至少检索选择文本?试试这个
def on_row_selected(self, container, row):
print(row.widget.label)
给出回溯:
Traceback (most recent call last):
File "/home/user/Documents/App/player.py", line 45, in on_row_selected
print(row.widget.label) # or data, value, text - nothing works
RuntimeError: unable to get the value
行变量的类型
<Gtk.ListBoxRow object at 0x7f9fe7604a68 (GtkListBoxRow at 0x5581a51ef7d0)>
所以上面的代码,我认为,应该像魅力一样工作......但事实并非如此。
非常感谢您提供的任何帮助!
解决方案
因此,您需要分配选择:
treeview_selection = treeview.get_selection()
并将其与“已更改”信号连接:
treeview_selection.connect('changed', on_tree_selection_changed)
然后,您可以使用以下方法获取所需的数据:
def on_tree_selection_changed(self, treeview):
model, treeiter = treeview.get_selected()
if treeiter is not None:
print(model[treeiter][0]) # you should a list index to get the data you require for each row - first column = [0], second column = [1] etc.
我建议您阅读pgi 文档以及python Gtk 文档