user3601487
user3601487

Reputation: 1107

Kivy How to create a popup with size adjustable to its contents?

I'm trying to create a rule in KV language, which then I could use to display errors or warnings. The problem is that, by default, the popup takes all of the size available for the parent window. I would like it to be adjustable to its contents, in this case a Label and a Button. By that I mean that popup should have the minimal size to properly display all of its contents. My code looks like this:

popup.py

from kivy.app import App
from kivy.factory import Factory
from kivy.uix.popup import Popup

class PopupApp(App):

    def build(self):
        popup = Factory.ErrorPopup()
        popup.message.text = "This text should fit in the popup."
        popup.open()

if __name__ == '__main__':
    PopupApp().run()

popup.kv

#:kivy 2.0

<ErrorPopup@Popup>:
    message: message
    auto_dismiss: False
    title: "Error"
    
    GridLayout:
        cols: 1
        Label: 
            id: message
        AnchorLayout:
            anchor_x: "center"
            anchor_y: "bottom"
            Button:
                text: 'Close'
                size_hint: None, None
                size: self.texture_size
                padding: [10, 5]
                on_release: root.dismiss()

This is what I have: current

I want something like this: enter image description here

Upvotes: 0

Views: 927

Answers (1)

John Anderson
John Anderson

Reputation: 38962

Here is a hack to do that in the kv:

<ErrorPopup@Popup>:
    message: message
    auto_dismiss: False
    title: "Error"
    size_hint: None, None
    width: grid.width + dp(25)
    height: grid.height + root.title_size + dp(48)
    
    GridLayout:
        id: grid
        size_hint: None, None
        size: self.minimum_size
        padding: [10, 5]
        cols: 1
        AnchorLayout:
            anchor_x: "center"
            anchor_y: "bottom"
            size_hint: None, None
            height: message.height
            width: max(message.width, butt.width)
            Label: 
                id: message
                size_hint: None, None
                size: self.texture_size
                padding: [10, 5]
        AnchorLayout:
            anchor_x: "center"
            anchor_y: "bottom"
            size_hint: None, None
            height: butt.height
            width: max(message.width, butt.width)
            Button:
                id: butt
                text: 'Close'
                size_hint: None, None
                size: self.texture_size
                padding: [10, 5]
                on_release: root.dismiss()

This calculates widths and heights to minimize the size of the Popup.

Upvotes: 2

Related Questions