首页 > 解决方案 > 箭头键通过 Gtk.FlowBox.select_child() 忽略选择

问题描述

当我以编程方式使用 Gtk.FlowBox.select_child() 时,选择工作正常。但是,如果我之后使用箭头键移动选择,它会忽略先前选择的项目并从 FlowBox 中的第一项移动。我不知道这是一个错误还是我必须做其他事情才能使光标知道新位置。用鼠标选择按预期工作。

我在 Linux 上使用 gtk3 版本 3.24.23。

import os
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GdkPixbuf

# just a folder with a bunch of png images. 
ICON_DIR = os.path.expanduser("~/.icons")

class Window(Gtk.Window):
    
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(480, 400)
        self.scr_win = Gtk.ScrolledWindow(parent=self)
        self.flowbox = Gtk.FlowBox(parent=self.scr_win, homogeneous=True, 
                row_spacing=8, column_spacing=8, min_children_per_line=4, 
                max_children_per_line=100)
        
        for i, icon_name in enumerate(os.listdir(ICON_DIR)):
            self.flowbox.insert(
                    Gtk.Image.new_from_pixbuf( 
                    GdkPixbuf.Pixbuf.new_from_file_at_size(
                    os.path.join(ICON_DIR, icon_name), 64, 64)), i)
        
        self.show_all()

        # selecting the 51st item just as an example:
        selected = self.flowbox.get_child_at_index(50)
        self.flowbox.select_child(selected)
        self.scr_win.get_vadjustment().set_value(selected.get_allocation().y)
            
if __name__ == "__main__":
    win = Window()
    win.connect("destroy", Gtk.main_quit)
    Gtk.main()
    
    

标签: pythongtk3

解决方案


我所要做的就是在选择之后抓住焦点:

selected.grab_focus()

推荐阅读