我想将开关对准BoxLayout的左侧。对于标签,我使用以下代码实现了这一点:
text_size: self.size
这会将我的标签文本放置在BoxLayout的左下角。但是,我无法使用switch小部件进行相同的操作。我尝试玩过size_hint_x,size,pos等,但是我不能在不干扰盒子大小的情况下正确对齐元素。目前,我的标签正确对齐,因此我尝试为它们分配ID,并根据标签的当前位置使用以下命令调整开关的方向:
BoxLayout:
padding: 100, 0, 0, 0
orientation: 'horizontal'
text_size: self.size
valign: 'middle'
Label:
text: 'this is already correctly aligned'
id: 'labelCorrectlyAligned'
#Some other code
BoxLayout:
padding: 100, 0, 0, 0
orientation: 'horizontal'
#here i need something like text_size: self.size but for switches
Switch:
size_hint_x: labelCorrectlyAligned.pos[0] #this should be the current X-position of the label
#pos_hint_x: labelCorrectlyAligned.pos[0] #didnt work either
如果我正确理解了您的问题,您可以按照size
中的说明将Switch
的documentation设置为最小值。
所需的最小尺寸为83x32像素
任何比该尺寸大的尺寸都将使83 x 32图像居中于该较大尺寸。
而且,在这些布局情况下,我发现对Widgets
的背景进行着色有助于轻松准确地查看它们的位置和大小。这是您的“ kv”的修改后的版本,可同时满足以上两个建议:
BoxLayout:
orientation: 'vertical'
BoxLayout:
padding: 100, 0, 0, 0
orientation: 'horizontal'
canvas.before:
Color:
rgba: 1,0,0,1
Rectangle:
pos: self.pos
size: self.size
Label:
text: 'this is already correctly aligned'
text_size: self.size
valign: 'middle'
id: 'labelCorrectlyAligned'
canvas.before:
Color:
rgba: 0,1,0,1
Rectangle:
pos: self.pos
size: self.size
# Some other code
BoxLayout:
padding: 100, 0, 0, 0
orientation: 'horizontal'
canvas.before:
Color:
rgba: 1,1,0,1
Rectangle:
pos: self.pos
size: self.size
Switch:
size_hint: None, None
size: 83, 32
on_active: app.setBluetoothConnection(self)
canvas.before:
Color:
rgba: 0,0,1,1
Rectangle:
pos: self.pos
size: self.size
当然,当您对布局满意时,只需移除canvas.before:
块。
顺便说一下,text_size
和valign
在BoxLayout
中无效,它们必须在Label
规则中。
因此,Switch
和Label
都在BoxLayout
的左侧。确定Label
大小的常用方法是使用:
size_hint: None, None
size: self.texture_size
这为您提供Label
的最小尺寸。