Kivy - Create new widget and set its position and size

穿精又带淫゛_ 提交于 2020-01-03 06:32:12

问题


got a little problem. So Iam trying to create my own widget, and i have succeed, only except for setting its size and position right(to be same as its parrent).

class Story(App):
    def build(self):    
        return MyWidgets().init()

The app has GridLayout as a holder, into which i want to pass the StoryWidget

class MyWidgets(object):

    def init(self):
        root = GridLayout(cols=2,rows=1)
        root.add_widget(StoryWidget())
        root.add_widget(Button())
        return root

Story Widget goes as this:

class StoryWidget(Widget):
    def __init__(self,**kwargs):
        super(StoryWidget, self).__init__(**kwargs)
        topLayout=BoxLayout(orientation = "vertical")
        topLayout.add_widget(Button(text="first"))
        topLayout.add_widget(Button(text="second"))
        self.add_widget(topLayout)

If I try to get the background color to it, it works fine:

        with self.canvas.before:
            Color(.9,.9,1)  
            self.Backgroud = Rectangle(pos=self.pos,size=self.size)

        self.bind(pos=self.repaint,size=self.repaint)
        self.bind(pos=self.resize,size=self.resize)

    def repaint(self,*args):
        self.Backgroud.pos = self.pos
        self.Backgroud.size = self.size

The whole firs column of root(Gridlayout) gets correctly repainted in white, but the Widget stands on defaut pos(0,0) and default size(100,100). From what i know, its because Widget cant handle these things. Layout should do it automatically somehow. As can be seen, the root widget of StoryWidget is layout. I do not know why it`s not working. I tried to inherit from the Layout instead of Widget, but still nothing. Any advice? Thanks!


回答1:


Alright, i have figured it out, turns out i forgot to set appropriate attributes. So Iam now using Gridlayout instead of BoxLayout, in which case it needs cols and rows so it should now look like this:

class StoryWidget(GridLayout):
    def __init__(self,**kwargs):
        self.cols=1
        self.rows=1
        super(StoryWidget, self).__init__(**kwargs)
        topLayout=BoxLayout(orientation = "vertical")
        topLayout.add_widget(Button(text="first"))
        topLayout.add_widget(Button(text="second"))
        self.add_widget(topLayout)

    with self.canvas.before:
        Color(.9,.9,1)  
        self.Backgroud = Rectangle(pos=self.pos,size=self.size)

    self.bind(pos=self.repaint,size=self.repaint)
    self.bind(pos=self.resize,size=self.resize)


来源:https://stackoverflow.com/questions/30654385/kivy-create-new-widget-and-set-its-position-and-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!