滚动到 GtkListBox 中选定的行

ykt*_*too 6 gtk go gtk3

我在这里有点没有主意。我想要一件非常简单的事情:能够GtkListBox以编程方式选择给定行,然后滚动列表框(包含在 aScrolledWindow和 a中Viewport)。

选择一行很简单(我的代码是 Go & gotk3,但这并不那么重要):

listBox.SelectRow(row)
Run Code Online (Sandbox Code Playgroud)

但事实证明,滚动到该行是一个真正的挑战。无论我尝试什么,我都失败了:

  • 我试图集中注意力,但没有任何帮助
  • 我尝试使用 找出该行的 Y 坐标gtk_widget_translate_coordinates(),但它对任何行返回 -1
  • 也许我可以找出列表框顶部和底部的哪一行,并使用它来滚动,ScrolledWindow但我不知道如何做到这一点。

更新:我已经尝试过这里建议的内容:Manually roll to a child in a Gtk.ScrolledWindow,但它不起作用,因为仍然没有发生滚动:

listbox.SelectRow(rowToSelect)
listbox.SetFocusVAdjustment(listbox.GetAdjustment())
if rowToSelect != nil {
    rowToSelect.GrabFocus()
}
Run Code Online (Sandbox Code Playgroud)

我也使用下面的代码对 的孩子进行了相同的尝试rowToSelect,但无济于事:

if c, err := rowToSelect.GetChild(); err == nil {
    c.GrabFocus()
}

Run Code Online (Sandbox Code Playgroud)

ykt*_*too 5

感谢 Emmanuel Touzery 的提示,我终于搞定了。我不必使用计时器,但问题确实是在填充列表框时,该行尚未实现,因此不可能发生坐标转换。

我所做的是使用 GLib 安排滚动idle_add(),这使得它稍后在下游发生,并且这似乎工作得很好:有关详细信息,请参阅此提交。

简而言之,这一切都归结为以下代码:

func ListBoxScrollToSelected(listBox *gtk.ListBox) {
    // If there's selection
    if row := listBox.GetSelectedRow(); row != nil {
        // Convert the row's Y coordinate into the list box's coordinate
        if _, y, _ := row.TranslateCoordinates(listBox, 0, 0); y >= 0 {
            // Scroll the vertical adjustment to center the row in the viewport
            if adj := listBox.GetAdjustment(); adj != nil {
                _, rowHeight := row.GetPreferredHeight()
                adj.SetValue(float64(y) - (adj.GetPageSize()-float64(rowHeight))/2)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

必须使用and 来调用上述函数glib.IdleAdd(),而不是在填充列表框的代码中调用。