我在 kivy 中有一个简单的用户界面,它由一个大网格布局内的多个网格布局组成。
守则
这是接口(interface)的kv代码
Builder.load_string('''
<GreyLabel>:
size_hint_y: None
height: 30
canvas.before:
Color:
rgba: .7, .7, .7, 1
Rectangle:
pos: self.pos
size: self.size
<ContainerBox>:
orientation: 'horizontal'
GridLayout:
cols: 1
row_force_default: True
foo: [self.rows_minimum.update({i: x.height}) for i, x in enumerate(reversed(list(self.children)))]
ResizingFrame:
id: Row1
cols: 1
GreyLabel:
text: "Something goes here"
GridLayout:
id: Row2
cols: 1
Label:
height: 30
text: 'Label One'
canvas.before:
Color:
rgba: .4, .4, .4, 1
Rectangle:
pos: self.pos
size: self.size
TextInput:
height: 30
multiline: False
write_tab: False
hint_text: 'Insert one liner'
GridLayout:
id: Row3
cols: 1
Label:
height: 45
text: 'Label two'
Button:
text: 'Button One'
height: 60
GridLayout:
rows: 1
height: 25
Button:
text: 'Button Two'
Button:
text: 'Button three'
''')
注意ResizingFrame
项。这是一个 GridLayout
类,其代码如下
class ResizingFrame(GridLayout):
c_value = StringProperty('SomeThing goes here')
def __init__(self, **kwargs):
super(ResizingFrame, self).__init__(**kwargs)
Clock.schedule_once(lambda dt: self.adjustHeight(), 1)
def adjustHeight(self):
print("ResizingFrame.adjustHeight() before:", self.height)
self.height = 40
print("ResizingFrame.adjustHeight() after:", self.height)
您可以找到完整代码here .
目标
我希望能够更改 ResizingFrame
的高度。
界面一开始看起来像这样:
每当 adjustHeight()
运行时,它会显示:
ResizingFrame.adjustHeight()之前:100
ResizingFrame.adjustHeight() 之后:40
但由于某种原因,这种高度变化实际上从未发生过。我根本无法更改 ResizingFrame
的高度。为什么会发生这种情况?我该如何解决它?
注意
这与this question有关.
我怀疑问题与以下行有关:
foo: [self.rows_minimum.update({i: x.height}) for i, x in enumerate(reversed(list(self.children)))]
这应该将行的最小高度设置为其子行的高度。但正如您在屏幕截图 1 中看到的那样,这种情况并没有发生。它只是将最小高度设置为 100,之后我无法更改高度。我什至无法将高度增加到 100 以上。它只是卡住了。
最佳答案
您无法更改 ResizingFrame
大小的原因是它的 size_hint
优先于任何大小更改。因此,将您的 adjustHeight
方法修改为:
def adjustHeight(self):
print("ResizingFrame.adjustHeight() before:", self.height)
self.size_hint_y = None
self.height = 40
print("ResizingFrame.adjustHeight() after:", self.height)
将允许高度
更改生效。
请注意,如果不将 size_hint_y
设置为 None
,您将更改 height
属性,并且会打印更改后的值。但是,一旦您的 adjustHeight
方法完成,就会重新计算 ResizingFrame
高度并改回 100。您可以通过调用原始 adjustHeight
方法来查看这一点多次(之前的 height
将始终返回 100)。
关于python - Kivy:无法更改嵌套 GridLayout 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57386386/