我有一个自定义小部件Message,它由一个TextInput、一个Button和一个Label组成。TextInput是不可编辑的,其目的只是显示文本。但是我很难调整它的大小以适应文本。我见过有人问动态高度,他有一个答案可以做类似wdg.height = (len(wdg._lines) + 1) * wdg.line_height。虽然这个方法对高度确实很有效,但我不确定如何实现宽度方面的类似功能。可能存在某种line_width属性?我想把字体大小和最长的一行相乘,但是不同字母所占的大小不一致,而且我看不到预测换行的方法,所以这是一个问题。有更好的变种吗?
下面是我定义小部件的代码:Builder.load_string('''
:
FloatLayout:
pos: root.pos
width: self.width
height: self.height
canvas:
Color:
rgba: 0, 0, 0, 1
RoundedRectangle:
pos: root.pos
size: self.size
Color:
rgba: 1, 1, 1, 1
RoundedRectangle:
pos: root.x + 1, root.y + 1
size: self.width - 2, self.height - 2
Button:
id: bt
pos: root.pos
size: self.size
background_normal: ''
background_down: ''
background_color: 0, 0, 0, 0
on_press: root.test()
MyTextInput:
pos: root.pos
size: bt.size
id: msg
background_color: 0, 0, 0, 0
readonly: True
text: str(msg)
cursor_color: 0, 0, 0, 0
Label:
x: root.x + 65
y: root.y - 15
size: 40, 2
id: time
color: 0, 0, 0, 1
font_size: 10
''')
class Message(Widget):
def __init__(self, **kwargs):
super(Message, self).__init__(**kwargs)
def test(self, *args, **kwargs):
print("Touch received")
以及build方法中负责创建这些小部件的函数:
^{pr2}$
其中tx1_main是我从(TextInput)获得文本的地方,sv1_main是一个ScrollView,它显示了显示这些消息小部件的FloatLayout(msg_float)。在