Как правильно выровнять мой компонент qml? - PullRequest
1 голос
/ 05 мая 2019

Я пытаюсь написать простое приложение QML, которое будет состоять из множества повторяющихся элементов, организованных в строки.Результат будет аналогичен представленному ниже: enter image description here

В настоящее время у меня есть повторяющийся фрагмент кода, который достигает этой цели:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Controls.Material 2.3
import QtQuick.Layouts 1.12

ApplicationWindow {
    Material.theme: Material.Dark
    visible: true
    width: 480
    height: 640
    title: qsTr("Hello world!")
    id: root

    GridLayout {
        anchors.horizontalCenter: parent.horizontalCenter
        columns: 3

        Text {
            color: "white"
            text: "aaa"
            font.family: "Ubuntu"
            font.pixelSize: 20
        }
        SpinBox {
            from: 0
            to: 1000
            stepSize: 1
            editable: true
        }
        Rectangle {
            width: 40
            height: 20
            color: "#F48FB1"
            Text {
                font.family: "Ubuntu"
                font.pixelSize: 16
                text: "ml"
                anchors.verticalCenter: parent.verticalCenter
                anchors.horizontalCenter: parent.horizontalCenter
            }
        }

        Text {
            color: "white"
            text: "bbb"
            font.family: "Ubuntu"
            font.pixelSize: 20
        }
        SpinBox {
            from: 0
            to: 100
            stepSize: 1
            editable: true
        }
        Rectangle {
            width: 40
            height: 20
            color: "#F48FB1"
            Text {
                font.family: "Ubuntu"
                font.pixelSize: 16
                text: "%"
                anchors.verticalCenter: parent.verticalCenter
                anchors.horizontalCenter: parent.horizontalCenter
            }
        }
        Text {
            color: "white"
            text: "ccc"
            font.family: "Ubuntu"
            font.pixelSize: 20
        }
        SpinBox {
            from: 0
            to: 100
            stepSize: 1
            editable: true
        }
        Rectangle {
            width: 40
            height: 20
            color: "#F48FB1"
            Text {
                font.family: "Ubuntu"
                font.pixelSize: 16
                text: "%"
                anchors.verticalCenter: parent.verticalCenter
                anchors.horizontalCenter: parent.horizontalCenter
            }
        }
    }
}

Однакокаждая строка имеет одинаковую структуру, поэтому я попытался извлечь компонент из кода:

Item {
id: ingredient
property alias ingredientText: qualifier.text
property alias ingredientMaxValue: amount.to
property alias ingredientUnit: unit.text

RowLayout {
    Text {
        id: qualifier
        color: "white"
        text: "asdf"
        font.family: "Ubuntu"
        font.pixelSize: 20
    }
    SpinBox {
        id: amount
        from: 0
        to: 1000
        stepSize: 1
        editable: true
    }
    Rectangle {
        width: 40
        height: 20
        color: "#F48FB1"
        Text {
            id: unit
            font.family: "Ubuntu"
            font.pixelSize: 16
            text: "unit"
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter
            }
        }
    }
}

К сожалению, когда я пытаюсь использовать свой компонент в главном окне, он не выравнивается и выходит извидимая часть этого (я вижу его снова после увеличения окна):

ApplicationWindow {
Material.theme: Material.Dark
visible: true
width: 480
height: 640
title: qsTr("Hello world!")
id: root

GridLayout { // I know now it will not work properly for sure,
    //  but i tried using other layouts and alignment methods
    //  and it didn't help me at all
    anchors.horizontalCenter: parent.horizontalCenter
    columns: 3
    Ingredient {
        ingredientMaxValue: 100; ingredientText: "qwerty"; ingredientUnit: "kg"
        }
    }
}

enter image description here

Вопрос в том, как добиться выравнивания элементовкак на первом рисунке, используя компоненты «Ингредиент»?

Ответы [ 2 ]

1 голос
/ 05 мая 2019

Проблема была в якорях .Вы должны прочитать об этом, это поможет вам в будущем.Вы можете попробовать поэкспериментировать с якорями, чтобы выбрать наилучшее для вас положение.

Кратко об якорях.Якоря автоматически установят положение для настройки элемента на экране.Также я рекомендую прочитать о столбце , строке и сетке .

enter image description here

ApplicationWindow {
    Material.theme: Material.Dark
    visible: true
    width: 480
    height: 640
    title: qsTr("Hello world!")
    id: root

    GridLayout {
        anchors.fill: parent
        columns: 3
        Item {
            id: ingredient
            anchors.fill: parent

            property alias ingredientText: qualifier.text
            property alias ingredientMaxValue: amount.to
            property alias ingredientUnit: unit.text

            RowLayout {
                anchors.right: parent.right
                anchors.left: parent.left
                anchors.top: parent.top
                Text {
                    id: qualifier
                    color: "white"
                    text: "asdf"
                    font.family: "Ubuntu"
                    font.pixelSize: 20
                }
                SpinBox {
                    id: amount
                    from: 0
                    to: 1000
                    stepSize: 1
                    editable: true
                }
                Rectangle {
                    width: 40
                    height: 20
                    color: "#F48FB1"
                    Text {
                        id: unit
                        font.family: "Ubuntu"
                        font.pixelSize: 16
                        text: "unit"
                        anchors.verticalCenter: parent.verticalCenter
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                }
            }
        }
    }
}
1 голос
/ 05 мая 2019

У вас есть следующие ошибки:

  • Размер ваших детей не учитывается при расчете размера предмета.Чтобы вычислить правильный размер, вы можете использовать implicitWidth и implicitHeight для RowLayout.
  • Вы не должны использовать GridLayout, потому что, как вы указываете, каждый Ingredient является элементом, в этом случае вы должны использовать ColumnLayout.

Ingredient.qml

import QtQuick 2.0
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.5

Item {
    id: ingredient
    property alias ingredientText: qualifier.text
    property alias ingredientMaxValue: amount.to
    property alias ingredientUnit: unit.text

    width: rl.implicitWidth
    height: rl.implicitHeight

    RowLayout {
        id: rl
        Text {
            id: qualifier
            color: "white"
            text: "asdf"
            font.family: "Ubuntu"
            font.pixelSize: 20
        }
        SpinBox {
            id: amount
            from: 0
            to: 1000
            stepSize: 1
            editable: true
        }
        Rectangle {
            width: 40
            height: 20
            color: "#F48FB1"
            Text {
                id: unit
                font.family: "Ubuntu"
                font.pixelSize: 16
                text: "unit"
                anchors.verticalCenter: parent.verticalCenter
                anchors.horizontalCenter: parent.horizontalCenter
            }
        }
    }
}

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Controls.Material 2.3
import QtQuick.Layouts 1.12

ApplicationWindow {
    Material.theme: Material.Dark
    visible: true
    width: 480
    height: 640
    title: qsTr("Hello world!")
    id: root

    ColumnLayout{
        width: parent.width
        height: implicitHeight
        Ingredient{
            Layout.alignment: Qt.AlignHCenter
            ingredientMaxValue: 100; ingredientText: "qwerty"; ingredientUnit: "kg"
        }
        Ingredient{
            Layout.alignment: Qt.AlignHCenter
            ingredientMaxValue: 100; ingredientText: "qwerty"; ingredientUnit: "kg"
        }
        Ingredient{
            Layout.alignment: Qt.AlignHCenter
            ingredientMaxValue: 100; ingredientText: "qwerty"; ingredientUnit: "kg"
        }
    }

}

enter image description here

...