简体   繁体   中英

Kivy Label text wrap in scroll widget

I'm trying to make a simple chat streamer. What I am struggling with is to get the chat message align left and have the text wrapped dynamically according to the window size.

The idea is to have chat messages being displayed as labels in a grid layout.

class ChatMessage(Label):

    def __init__(self, *args, **kwargs):
        super(ChatMessage, self).__init__(*args, **kwargs)
        self.text_size = self.size
        self.halign = 'left'

class Root(ScreenManager):

    def __init__(self, *args, **kwargs):
        super(ScreenManager, self).__init__(*args, **kwargs)
        self.ids.chatstream.bind(minimum_height=self.ids.chatstream.setter('height'))
        self.add_message()


    def add_message(self):
        for x in xrange(50):
            label = ChatMessage(text='Im still not completely sure I understand the mechanisms at work here, though.. Im still not completely sure I understand the mechanisms at work here, though.. Im still not completely sure I understand the mechanisms at work here, though.' + str(x))

            self.ids.chatstream.add_widget(label)
            self.ids.scroller.scroll_y = 0

the kv file:

<Root>:
    Screen:
        name: 'main'
        BoxLayout:
            orientation: 'vertical'
            Button:
                text: ''
                on_release: app.root.current = 'chat'

    Screen:
        name: 'chat'
        BoxLayout:
            orientation: 'vertical'
            ScrollView:
                id: scroller
                do_scroll_x: False
                GridLayout:
                    id: chatstream
                    cols: 1
                    padding: (10, 15)
                    spacing: 20
                    size_hint_y: None
            Button:
                text: ''
                on_release: app.root.current = 'main' 

Set the size of your ChatMessage instances, eg

<ChatMessage>
    size_hint_y: None
    height: self.texture_size[1]  # the size needed to fit the text
    text_size: self.width, None

Also remove the text_size setting in the python size. You can remove the __init__ entirely if you set the halign in kv too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM