如何理解和使用BoxLayout中的size_hint?

最近使用Kivy进行简单的图形用户界面开发。在使用BoxLayout时,发现size_hint的行为跟预期的不一致,特此记录分析一下。

当BoxLayout中所有的Widget都定义了size_hint时,所有Widget的尺寸符合预期

完整代码如下。

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.clock import Clock

kv = Builder.load_string(
    """

    bold: True
    font_size: self.height / 2
    text_size: self.size
    valign: "middle"
    halign: "center"
    opacity: 1 if self.text else 0
    canvas.before:
        Color:
            rgb: .6, .6, .6
        Rectangle:
            pos: self.pos
            size: self.size

BoxLayout:
    orientation: "vertical"
    padding: 1
    spacing: 1

    ActionLabel1:
        id: step1
        size_hint: 1, 0.2

    ActionLabel1:
        id: step2
        size_hint: 0.5, 0.8
"""
)

class MyLabel(Label):
    pass


def gen():
    while True:
        yield ["123", "456"]


class MyApp(App):
    def build(self):
        self.gen = gen()
        self.update()
        self._timer = Clock.schedule_interval(self.update, 3.0)
        return kv

    def update(self, /, *args):
        l = next(self.gen)
        for i, text in enumerate(l, start=1):
            l1 = kv.ids[f"step{i}"]
            l1.text = text


MyApp().run()

运行结果:


Screen Shot 2021-10-08 at 11.14.26 pm.png

当BoxLayout中只有部分Widget定义size_hint时,Widget尺寸与预期不一致

比如,当把第一个ActionLabelsize_hint注释掉,此时运行结果如下。

Screen Shot 2021-10-08 at 11.20.52 pm.png

第二个ActionLabel的宽度符合预期,但高度并不是预期的总高度x0.8。这究竟是怎么回事呢?

看了一下BoxLayout的源码,才明白其中的原因。Widget默认的size_hint(1,1),所以第一个ActionLabel的size_hint是(1,1),第二个是(0.5, 0.8)。因为BoxLayout的orientationvertical,所以横向的长度没有问题,但纵向的高度会有问题。

BoxLayout在分配Widget的高度时,第一个ActionLabel是layout_height * 0.8 / (1+0.8),第二个是layout_height * 1 / (1+0.8),也就是上图的运行结果。

我自己潜意识认为第二个ActionLabel的size_hint_y是0.8,那么第一个的size_hint_y则应该是1-0.8=0.2。这一点与Widget默认的size_hint_y=1不符,造成了误解。

总结

遇到违反预期的现象时,需要仔细阅读文档和源码。源码面前无秘密,总会找到合理的解释的。

你可能感兴趣的:(如何理解和使用BoxLayout中的size_hint?)