首页 > 解决方案 > 为什么孩子的 Kivy ScrollView 孩子不可滚动?

问题描述

这是运行 kivy 的 python 脚本的一部分

class someclass(Widget):
# code
# code
Clock.schedule_interval(self.timeandlog, 0.1)
self.x = 20
def timeandlog(self,dt):
    if condition == True: # 
       self.ids.pofchild.add_widget(Label(text=logmsg, pos = (10, self.x)))
       self.x = self.x + 10   ### just playing with position 
       condition = False  

.kv 文件:

<someclass>

    #somelabels and buttons:

    ScrollView:
        do_scroll_x: False
        do_scroll_y: True
        pos: root.width*0.3, root.height*0.7
        size: root.width*0.8, root.height*0.7 
        Widget:
            cols: 1 
            spacing: 10
            id: pofchild

现在我知道ScrollView接受了Widget,所以我只添加了一个,id: pofchild然后我在其中添加了标签,self.ids.pofchild.add_widget(Label()并更改了每个新标签pospos=(20, self.x)但标签不可滚动,仅填充小部件高度然后停止出现。什么是正确的属性,所以它们可以滚动?

标签: pythonkivyscrollview

解决方案


通常,当您希望 aWidget包含 otherWidgets时,您应该使用 a Layout Widget。一个简单Widget的不尊重size_hintor pos_hint,所以一个简单的孩子Widget通常以 (100,100) 的默认大小和 (0,0) 的默认位置结束。

所以,一个好的开始是改变:

class someclass(Widget):

类似于:

class Someclass(FloatLayout):

请注意,类名以大写字母开头。虽然它不会在您的示例中造成任何困难,但是当您使用kv并且您的类名以小写字母开头时,它可能会产生错误。

同样, the 的孩子ScrollView通常也是 a Layout。一种可能性是GridLayout,像这样:

    GridLayout:
        size_hint_y: None
        height: self.minimum_height
        cols: 1 
        spacing: 10
        id: pofchild

这里的键属性是size_hint_y: Noneheight: self.minimum_height。它们允许GridLayout随着更多子项的添加而增长,并且其高度将被计算为包含子项所需的最小高度。

然后,您可以像这样添加孩子:

self.ids.pofchild.add_widget(Label(text=logmsg, pos=(10, self.x), size_hint_y=None, height=50))

由于我们期望GridLayout计算其最小高度,因此我们必须为其子项提供显式height,因此size_hint_y=None, height=50.


推荐阅读