在列表框中制作多个复选按钮的"全选"按钮



我正在尝试制作一个列表,其中每行都有一个复选框,在此列表的顶部,我想要一个"全选/取消全选"选项。问题是我什至无法弄清楚如何在CheckButtons之间迭代以使用"Gtk.CheckButton.Set_activate(True)"之类的东西。我完全迷失了这个问题。

到目前为止,这是我的代码

class ListChapters(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="List of Itens")
self.set_border_width(10)
box_outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.add(box_outer)
listbox = Gtk.ListBox()
listbox.set_selection_mode(Gtk.SelectionMode.NONE)
box_outer.pack_start(listbox,False, False, 0)
row = Gtk.ListBoxRow()
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
row.add(hbox)
label = Gtk.Label('Marcar/Desmarcar tudo.', xalign=0)
checkall = Gtk.CheckButton()
hbox.pack_start(label, True, True, 0)
hbox.pack_end(checkall, False, True, 0)
listbox.add(row)
checkall.connect("toggled", self.mark_all)
listbox2 = Gtk.ListBox()
listbox2.set_selection_mode(Gtk.SelectionMode.NONE)
box_outer.pack_start(listbox2, True, True, 0)
index = ['Item1','Item2','Item3']
for i in index:
row = Gtk.ListBoxRow()
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
row.add(hbox)
cap = Gtk.Label(i, xalign=0)
check = Gtk.CheckButton()
hbox.pack_start(cap, True, True, 0)
hbox.pack_start(check, False, True, 0)
listbox2.add(row)
check.connect("toggled", self.on_check_marked)

问题:选择列表框中的多个复选框的"全部"按钮
...我什至无法弄清楚如何在复选框之间迭代

基本上你可以做到:

for boxrow in listbox2:

Gtk 3.0 (3.24.5) 文档:

  • 列表框
  • 切换按钮
  • Gtk.选择模式

  1. 定义您拥有自己的ListBoxRowGtk.ListBoxRow继承

    class ListBoxRow(Gtk.ListBoxRow):
    def __init__(self, label, **kwargs):
    super().__init__(**kwargs)
    
  2. 定义您的小部件并self.check成为class attribute

    hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
    self.add(hbox)
    cap = Gtk.Label(label, xalign=0)
    hbox.pack_start(cap, True, True, 0)
    self.check = check = Gtk.CheckButton()
    hbox.pack_start(check, False, True, 0)
    check.connect("toggled", self.on_check_marked)
    
  3. 定义要设置class methode checkbutton(...获取CheckButtonactive state

    def checkbutton(self, state=None):
    print('checkbutton({})'.format(state))
    if state is True:
    self.check.set_active(state)
    elif state is False:
    self.check.set_active(state)
    else:
    return self.check.get_active()
    
  4. 为了让check.connect(...开心...

    def on_check_marked(self, event):
    print('on_check_marked({})'.format(event))
    

用法

  1. 将您的ListBoxRow(...添加到listbox2

    for label in ['Item1','Item2','Item3']:
    row = ListBoxRow(label=label)
    listbox2.add(row)
    
  2. 迭代ListbBox,根据传递的CheckButton active state设置ListBoxRow中的所有CheckButton

    def mark_all(self, checkbox):
    for boxrow in self.listbox2:
    boxrow.checkbutton(state=checkbox.get_active())
    

用 Python 测试:3.5 - gi.__version__:3.22.0

最新更新