简体   繁体   中英

Kivy - Create new widget and set its position and size

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!

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)

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