Align text to edge of label in ScrollView in kivy

I am trying to make the Label scrollable horizontally and want halign:"right and valign:middle according to the code below

 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

+5
source share
1 answer

The decisive point here is the width of the text. If it is set to None , it is not limited, and if the text is wider than the parent, it can be scrolled. However, if the text requires only part of the width of the parent, the text will be centered inside the label (although a few lines will still be aligned to the right). On the other hand, if text_size statically set to a finite value, text that does not fit will wrap and will never scroll. The hacker solution is to set text_size: 8000, self.height (something very broad, is unlikely to ever happen). This allows you to scroll, but ugly (and you can accidentally scroll an area where nothing is displayed).

Instead, we dynamically change text_width . When text changes, we first remove the width limit. Then we let the label update its contents and set text_size as wide as possible to fit the text, but at least as wide as the parent.

Other settings make sure that the label itself is not less than the width of the parent ( width ) and that the ScrollView starts from the right edge ( scroll_x:1 )

Here is a complete example:

 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() 
+3
source

Source: https://habr.com/ru/post/1241873/


All Articles