Kivy - Как определить размер встроенных якорных макетов? - PullRequest
0 голосов
/ 26 июня 2019

Я хотел бы построить следующий простой дизайн в файле .kv.

design

Он состоит из 3 частей:

  • Один верхний левый анкерный макет, который состоит из сеточного макета из 3 столбцов. Я хочу, чтобы его ширина была равна 20% ширины окна, а его высота равнялась 75% высоты окна.
  • Один верхний правый анкерный макет, который состоит из вертикально ориентированного макета бокса. Я хочу, чтобы его ширина была равна 80% ширины окна, а его высота - 75% высоты окна.
  • Один нижний левый анкерный макет, который на данный момент пуст. Я хочу, чтобы его высота составляла 25% от высоты окна.

Эти три части сами включены в AnchorLayout.

Я попытался перевести этот дизайн в файл .kv следующим образом.

#:kivy 1.11.1

<Example>:
    anchor_x: "center"
    anchor_y: "center"

    AnchorLayout:
        anchor_x: "left"
        anchor_y: "top"
        size_hint: (0.2, 0.75)

        GridLayout:
            cols: 3
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"

    AnchorLayout:
        anchor_x: "right"
        anchor_y: "top"
        size_hint: (0.8, 0.75)

        BoxLayout:
            orientation: "vertical"
            Label:
                text: "HELLO..."
            Label:
                text: "WORLD..."

    AnchorLayout:
        anchor_x: "left"
        anchor_y: "bottom"
        size_hint: (1, 0.25)

        Label:
            text: "FOOTER"

Если это имеет значение, вот код моего .py файла.

# Importing Kivy
import kivy
kivy.require("1.11.1")

# Importing kivy libraries
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.lang import Builder


# Importing external libraries


# Import kv files
Builder.load_file("example.kv")


# Root widget of the application
class Example(AnchorLayout):
    pass


# Application class
class TestApp(App):
    def build(self, **kwargs):
        return Example()

# Launch the application
if __name__=="__main__":
    app = TestApp()
    app.run()

Вывод не выглядит так, как я ожидал, как показано на рисунке ниже:

screenshot2

Я не понимаю. Поскольку AnchorLayout является подклассом класса Widget и сам входит в состав Layout, его свойство size_hint должно позволить мне определить его размер.

Что мне здесь не хватает? Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 27 июня 2019

Проблема - дизайн по центру

Дизайн размещен в центре.

первопричина

Корнем является AnchorLayout со значением 'center' для anchor_x и anchor_y. Поэтому все его дочерние элементы (AnchorLayout s) расположены относительно корня.

Ниже приведен вид вашего дизайна в различных цветах для визуализации.

Design - canvas painted

AnchorLayout

AnchorLayout выравнивает свои дочерние элементы по границе (сверху, снизу, слева, справа) или по центру.

Решение

Существует три возможных решения для вашего дизайна. Предпочтение отдается методу 1.

Метод 1 - Нет AnchorLayout с

Этот метод заменяет все AnchorLayout с BoxLayout с. Он использует один виджет AnchorLayout меньше, что делает приложение более ресурсоэффективным, то есть использует меньше памяти, а приложение меньше.

Фрагменты - Метод 1

<Example>:
    orientation: 'vertical'

    BoxLayout:
        ...
        GridLayout:    # left box
            ...
        BoxLayout:    # right box
            ...
    BoxLayout:    # footer
        ...

Метод 2 - BoxLayout как root

Этот метод заменяет корневой виджет на BoxLayout и выравнивает левое поле.

Отрывки - Метод 2

<Example>:
    orientation: 'vertical'

    AnchorLayout:
        ...
        GridLayout:    # left box
            ...
        AnchorLayout:    # right box
            ...
    AnchorLayout:    # footer
        ...

Метод 3

Этот метод добавляет BoxLayout в качестве дочернего элемента корня, а остальные AnchorLayout в качестве дочернего элемента BoxLayout.

Отрывки - Метод 3

<Example>:
    anchor_x: "center"
    anchor_y: "center"

    BoxLayout:
        orientation: 'vertical'

        AnchorLayout:
            ...
            GridLayout:    # left box
                ...
            AnchorLayout:    # right box
                ...
        AnchorLayout:    # footer
            ...
* * Пример тысяча шестьдесят три * * 1 064

Метод 1 - Нет AnchorLayout с

main.py

from kivy.base import runTouchApp
from kivy.lang import Builder

runTouchApp(Builder.load_string("""

BoxLayout:
    orientation: 'vertical'

    BoxLayout:
        size_hint: 1, 0.75

        GridLayout:
            size_hint: 0.2, 1

            canvas.before:
                Color:
                    rgba: 1, 0, 0, 1
                Rectangle:
                    size: self.size
                    pos: self.pos

            cols: 3
            row_force_default: True
            row_default_height: 40

            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"            

        BoxLayout:
            orientation: 'vertical'

            canvas.before:
                Color:
                    rgba: 0, 1, 0, 1
                Rectangle:
                    size: self.size
                    pos: self.pos

            Label:
                text: "HELLO..."
            Label:
                text: "WORLD..."


    BoxLayout:
        size_hint: 1, 0.25

        canvas.before:
            Color:
                rgba: 0, 0, 1, 1
            Rectangle:
                size: self.size
                pos: self.pos

        Label:
            text: "FOOTER"

"""))

Вывод: метод 1 - нет AnchorLayout с

imageAnchorLayouts">

Метод 2 - BoxLayout как root

main.py

from kivy.base import runTouchApp
from kivy.lang import Builder

runTouchApp(Builder.load_string("""

BoxLayout:
    orientation: 'vertical'

    AnchorLayout:
        size_hint: 1, 0.75
        anchor_x: 'left'
        anchor_y: 'top'

        GridLayout:
            size_hint: 0.2, 1

            canvas.before:
                Color:
                    rgba: 1, 0, 0, 1
                Rectangle:
                    size: self.size
                    pos: self.pos

            cols: 3
            row_force_default: True
            row_default_height: 40

            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"            

        AnchorLayout:
            anchor_x: 'right'
            anchor_y: 'top'

            BoxLayout:
                orientation: 'vertical'
                size_hint: 0.8, 1

                canvas.before:
                    Color:
                        rgba: 0, 1, 0, 1
                    Rectangle:
                        size: self.size
                        pos: self.pos

                Label:
                    text: "HELLO..."
                Label:
                    text: "WORLD..."


    AnchorLayout:
        size_hint: 1, 0.25
        anchor_x: 'left'
        anchor_y: 'bottom'

        canvas.before:
            Color:
                rgba: 0, 0, 1, 1
            Rectangle:
                size: self.size
                pos: self.pos

        Label:
            text: "FOOTER"

"""))

Вывод: метод 2 - BoxLayout как root

imageBoxLayout as root">

0 голосов
/ 27 июня 2019

Изменение класса Example для расширения FloatLayout вместо AnchorLayout обеспечивает больший контроль над его дочерними элементами.С этим изменением на Example, вот kv, которое больше похоже на то, что вы хотите:

<Example>:
    AnchorLayout:
        anchor_x: "center"
        anchor_y: "top"
        size_hint: (0.2, 0.75)
        pos_hint: {'x':0, 'top':1}

        GridLayout:
            cols: 3
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"
            Button:
                text: "X"

    AnchorLayout:
        anchor_x: "center"
        anchor_y: "top"
        size_hint: (0.8, 0.75)
        pos_hint: {'right':1, 'top':1}

        BoxLayout:
            orientation: "vertical"
            Label:
                text: "HELLO..."
            Label:
                text: "WORLD..."

    AnchorLayout:
        anchor_x: "center"
        anchor_y: "bottom"
        size_hint: (1, 0.25)
        pos_hint: {'x':0, 'y':0}

        Label:
            text: "FOOTER"
...