为什么 Gtk.Entry() 不是由 set-width-chars() 设置的

Why isn't Gtk.Entry() set by set-width-chars()

可能是受骗者,但找不到匹配项。因为它(看似)简单,所以感觉像是我脑海中的一个盲点,但想不通。

问题

问题是Gtk.Entry似乎没有听从entry.set_width_chars(5)中定义的内容,但我找不到原因。我已将代码缩小到极简主义 window,以避免噪音:

#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


class InterFace:

    def __init__(self):
        
        win = Gtk.Window()
        maingrid = Gtk.Grid()
        win.add(maingrid)

        # the attach test
        label = Gtk.Label("Test123 ")
        maingrid.attach(label, 0, 0, 1, 1)
        entry = Gtk.Entry()
        entry.set_width_chars(5)
        maingrid.attach(entry, 1, 0, 1, 1)

        # ok, then the box test
        label2 = Gtk.Label("Test456 ")
        entry2 = Gtk.Entry()
        entry2.set_width_chars(5)
        box = Gtk.Box()
        maingrid.attach(box, 0, 1, 2, 1)
        box.pack_start(label2, False, False, 0)
        box.pack_start(entry2, False, False, 0)
        
        win.show_all()
        Gtk.main()
        
InterFace()

仍然显示:

显然超过 5 个字符。我错过了什么?

Gtk 计算每个小部件的实际大小的方式很复杂……至少对我来说是这样。

在这种情况下,您仅使用 set_width_chars() 设置条目的 "size request"。

here

Changes the size request of the entry to be about the right size for n_chars characters. Note that it changes the size request, the size can still be affected by how you pack the widget into containers. If n_chars is -1, the size reverts to the default entry size.

当 window 显示或调整大小时,条目 请求 至少 n_chars 宽度的大小。事实上,当您减小 window 大小时,您的条目也会减少,但不会超过 n_chars 个字符。让我们尝试使用 20 个字符,这将很清楚。有 5 个字符,条目将减少不超过 9 个字符,至少在我的机器上是这样......我认为因为即使是主要的 window 也有一个比标签和 5 个字符更大的大小请求条目。

如果需要,可以使用 set_max_width_chars()。在这种情况下,不会为条目分配大于 n_chars 的大小。也许这就是你想要的。

如果您在 set_max_width_chars() 和 set_width_chars() 中设置相同的数字,您将始终拥有相同大小的条目。