在kivy中将文本与ScrollView中的Label边缘对齐

时间:2016-01-30 07:44:34

标签: android python scroll label kivy

我正在尝试将Label水平滚动,并希望halign:"rightvalign:middle按照以下代码

ScrollView:

  Label:    
    id:maindisplay
    text:"0"
    font_size:"50sp"
    text_size: None ,self.height[1] #  Set the text wrap box height
    size_hint_x:None
    width: self.texture_size[0]

#Following part is not working
    halign: 'right'
    valign: 'middle'

enter image description here

1 个答案:

答案 0 :(得分:3)

这里的关键点是文本的宽度。如果它设置为None,则它不受约束,如果文本比父项宽,则可以滚动它。但是,如果文本仅需要父项宽度的一小部分,则文本将在标签内居中(尽管多行仍将右对齐)。另一方面,如果将text_size静态设置为有限值,则不适合的文本将换行并且永远不会滚动。 hacky解决方案是设置text_size: 8000, self.height(非常广泛,不太可能发生)。这允许滚动,但是很难看(并且可能会意外地滚动到没有显示任何内容的区域)。

相反,我们会动态更改text_width。当text更改时,我们首先删除宽度约束。然后我们让标签更新其内容,并将text_size设置为适合文本的宽度,但至少与父级一样宽。

其他设置可确保标签本身至少与父(width)一样宽,并且ScrollView从其右边缘开始(scroll_x:1

这是一个完整的例子:

from kivy.app import App
from kivy.lang import Builder
from kivy.config import Config
from kivy.clock import Clock
from kivy.properties import StringProperty, NumericProperty

kv = '''ScrollView:
  scroll_x: 1
  Label:
    canvas.before:
      Color:
        rgba:1,0,0,1
      Rectangle:
        pos: self.parent.pos
        size: self.size
    id:maindisplay
    text:"2"
    font_size:"50sp"
    text_size: None, self.height
    size_hint_x: None
    width:  max(self.texture_size[0], self.parent.width)
    halign: 'right'
    valign: 'middle'
    on_text: app.txt_cb(*args)
'''

class QApp(App):
    txt = StringProperty("1")
    num = NumericProperty(0)

    def add_string(self, dt=0):
        self.num += 1
        self.txt += "%i" % self.num
        self.root.ids.maindisplay.text = self.txt

    def txt_cb(self, obj, text):
        obj.text_size = (None, obj.height)
        obj.texture_update()
        obj.text_size = (max(obj._label.content_width, obj.parent.width), obj.height)

    def build(self):
        Clock.schedule_once(lambda dt:self.txt_cb(self.root.ids.maindisplay, ""), 0)
        Clock.schedule_interval(self.add_string, .5)
        return Builder.load_string(kv)

if __name__ == '__main__':
    QApp().run()