如何对齐列表视图标签?

时间:2019-04-07 15:43:07

标签: python kivy

我正在学习如何使用Kivy,我想知道如何在构建的列表视图中对齐标签。

默认情况下,标签居中,我想将所有标签向左对齐。

我的代码:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.listview import SimpleListAdapter
from kivy.uix.listview import ListView
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput

class TestApp(App):
    def build(self):
        messages = ["a", "b"]
        layout = BoxLayout(orientation='vertical')

        btn1 = Button(text='Hello')
        textinput = TextInput(text='Hello world', size_hint=(1, 0.1))
        messages.append("sd")
        simple_list_adapter = SimpleListAdapter(
            data=messages,
            cls=Label)
        simple_list_adapter.cls

        list_view = ListView(adapter=simple_list_adapter)
        layout.add_widget(list_view)
        layout.add_widget(textinput)
        return layout

TestApp().run()

1 个答案:

答案 0 :(得分:0)

一个简单的解决方案是创建具有所需对齐方式的标签

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.listview import SimpleListAdapter
from kivy.uix.listview import ListView
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput


class LeftLabel(Label):
    def __init__(self, **kwargs):
        super(LeftLabel, self).__init__(**kwargs)
        # https://kivy.org/doc/stable/api-kivy.uix.label.html#text-alignment-and-wrapping
        self.halign = "left"
        self.bind(size=self.setter("text_size"))


class TestApp(App):
    def build(self):
        messages = ["a", "b"]
        layout = BoxLayout(orientation="vertical")
        btn1 = Button(text="Hello")
        textinput = TextInput(text="Hello world", size_hint=(1, 0.1))
        messages.append("sd")
        simple_list_adapter = SimpleListAdapter(data=messages, cls=LeftLabel)
        list_view = ListView(adapter=simple_list_adapter)
        layout.add_widget(list_view)
        layout.add_widget(textinput)
        return layout


TestApp().run()

由于您是从奇特开始的,因此建议您学习RecycleView而不是ListView,因为后者是deprecated

  

从1.10.0版开始弃用:ListView已弃用,请改用RecycleView。