在QML布局中添加边距

4

我想给我的布局添加填充/边距,让我的控件不要太靠近窗口的边界。当我设置锚点边距时,它似乎并没有实际影响任何内容。

enter image description here

这是显示设置选项卡的QML文件。

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.2

Page {
    id: control

    title: qsTr("Settings")
    objectName: "SettingsView"


    ColumnLayout {
        spacing: 20

        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: parent.top

        Switch {
            text: qsTr("Theme")
            checked: root.Material.theme === Material.Dark
            Layout.fillWidth: true
            LayoutMirroring.enabled: true

            onClicked: {
                root.Material.theme = checked ? Material.Dark : Material.Ligth
                //Settings.currentTheme = root.Material.theme
            }
        }
    }
}

这是 main.qml 文件。

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.2

ApplicationWindow {
    id: root
    visible: true
    width: 300
    height: 500

    // Theme
    Material.theme: Material.Dark
    Material.accent: "#4096DD"
    Material.primary: "#4096DD"

    // Controls
    header: TabBar {
        id: tabBar
        currentIndex: swipeView.currentIndex
        TabButton {
            //text: qsTr("Home")
            icon.source: "qrc:/Images/home.svg"
        }
        TabButton {
            //text: qsTr("Settings")
            icon.source: "qrc:/Images/settings.svg"
        }
    }

    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: tabBar.currentIndex

        Page1 {
        }

        SettingsView {

        }

    }
}
1个回答

5

如果一个项目受到布局的影响,那么如果您想将所有边距设置为相同的值,则必须使用Layout.margins。但是,如果您想在每个方向上设置不同的边距,则必须使用Layout.leftMargin、Layout.topMargin、Layout.rightMargin和Layout.bottomMargin,在您的情况下:

ColumnLayout {
    spacing: 20

    anchors.left: parent.left
    anchors.right: parent.right
    anchors.top: parent.top

    Switch {
        <b>Layout.leftMargin: 20
        Layout.topMargin: 20
        Layout.rightMargin: 20</b>
        // ...

更新:

接着在锚点处设置边距:

ColumnLayout {
    spacing: 20

    anchors.left: parent.left
    anchors.right: parent.right
    anchors.top: parent.top

    <b>anchors.leftMargin: 20
    anchors.topMargin: 20
    anchors.rightMargin: 20</b>

    Switch {
        text: qsTr("Theme")
        // ...

我想在整个ColumnLayout上设置边距,而不仅仅是我的Switch控件。因为我将添加更多的控件,我希望它们都能从窗口边缘填充。 - JokerMartini
@JokerMartini FYI,一些项目除了0以外还有内部边距,因此如果未对齐,请考虑将这些边距设置为0。 - eyllanesc
嗯,似乎对任何东西都没有影响。 - JokerMartini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接