我有一个ScrollView()GridLayout(),它包含我正在处理的文本聊天程序的一些Label()对象 . 每条消息都会进入标签 . 我有标签包装文本很好,但我无法根据其中的文本数量优雅地设置标签的高度 .
ClientScreen()上的test()函数是有问题的函数 . 你可以在下面看到我的疯狂黑客 . 它运作正常,但我确信有比我更聪明,更聪明的人 . 我根本没有找到任何方法根据包装文本的数量来设置标签的高度而没有一些数学 .
你会注意到因为我的数学不准确,当你收缩并展开X轴上的Window()时,每个Label()之间的间距会增大 .
如果您需要更多信息,请告诉我,以下代码可以快速运行,以便您查看 .
谢谢你的帮助 .
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.lang import Builder
import math
Builder.load_string("""
<ClientScreen>:
GridLayout:
id: top_grid_layout
orientation: 'vertical'
cols: 1
ScrollView:
id: top_scroller
bar_width: 10
size: self.size
GridLayout:
id: text_scroll
orientation: 'vertical'
cols: 1
size_hint_y: None
height: self.minimum_height
ScrollView:
size: self.size
bar_width: 10
size_hint_y: 0.25
GridLayout:
id: grid_layout
padding: [10, 10, 10, 10]
orientation: 'vertical'
cols: 1
size_hint_y: None
row_default_height: 30
height: self.minimum_height
""")
class ClientScreen(Screen):
def __init__(self, **kwargs):
super(ClientScreen, self).__init__(**kwargs)
self.top_grid_layout = self.ids.top_grid_layout
self.grid_layout = self.ids.grid_layout
self.text_scroll = self.ids.text_scroll
self.top_scroller = self.ids.top_scroller
for x in range(0, 10):
text_input = Label()
text_input.padding_x = 10
text_input.size_hint_y = None
text_input.markup = True
text_input.text = 'A' + 'B' * 1000 + 'C'
text_input.font_size = '20sp'
self.test(text_input, text_input.size)
text_input.bind(size=self.test)
self.text_scroll.add_widget(text_input)
self.top_scroller.scroll_to(text_input)
for x in range(0, 5):
self.grid_layout.add_widget(Button(text='Test'))
def test(self, instance: Label, value):
#
# THIS IS THE FUNCTION THAT NEEDS CLEANING, SEE MY HORRIBLE HACK? :-)
#
font_size = instance.font_size
instance.text_size = instance.width, None
rows = len(instance.text) * (font_size * 0.621) / instance.width
rows = math.ceil(rows)
instance.height = rows * (font_size * 1.5)
class MyApp(App):
def build(self):
sm = ScreenManager()
sm.transition = NoTransition()
sm.add_widget(ClientScreen(name='client'))
return sm
MyApp().run()
1 回答
由于ykmm的以下问题解决了问题; https://gist.github.com/ykmm/9938073
这是我更新的代码,非常简单 . 调整标签大小时执行此代码 .