Qt Quick 2 / QML中的StackPanel等效项-宽度问题

时间:2019-05-09 07:01:50

标签: c++ qt qml

我正在尝试等效于wpf stackpanel,我已经有了一个逻辑并实现了它,但是宽度有些问题,我不知道如何在不进入宽度循环绑定的情况下创建新组件,这是我的堆栈面板:

StackPanel.qml

import QtQuick 2.12
import QtQuick.Controls 2.12
import KiMa.Models 1.0
Item {
    id:root
    property var orientation : UOrientation.Horizontal
    property int itemSpacing : 10
    default property list<Item> pageData
    Loader{
        property var childs
        anchors.fill: parent
        id:loader
        onChildsChanged: {
            if(root.pageData != null){
                for(var z = 0;z<root.pageData.length;++z){
                    root.pageData[z].parent = loader.childs
                }
            }
        }

    }
    state: orientation == UOrientation.Horizontal ? "row": "col"
    states: [
        State {
            name: "row"
            PropertyChanges {
                target: loader
                sourceComponent : row
            }
        },
        State{
            name: "col"
            PropertyChanges {
                target: loader
                sourceComponent : col
            }
        }

    ]
    Component{
        id:col
        Column{
            Component.onCompleted: {
                childs = _col;
            }
            id:_col
            width: parent.width
            spacing: root.itemSpacing
        }
    }
    Component{
        id:row
        Row{
            Component.onCompleted: {
                childs = _row
            }
            id:_row
            width: parent.width
            layoutDirection: Qt.RightToLeft
            spacing: root.itemSpacing
        }
    }
}

我的方向枚举是这样的:

#ifndef UORIENTATION_H
#define UORIENTATION_H
#include<QObject>

class UOrientation
{
    Q_GADGET
public:
    explicit UOrientation();
    enum Orientation{
        Horizontal,
        Vertical
    };
    Q_ENUM(Orientation)
};

#endif // UORIENTATION_H

和用法示例应如下所示:

StackPanel{
    x: 320
    height: 50
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 25
    Button{

    }
    Button{

    }
}

您需要将其添加到 main.cpp

qmlRegisterUncreatableType<UOrientation>("KiMa.Models",1,0,"UOrientation","its not creatable type!");

此代码有效,如果您有任何建议建议我更改,或者您认为我犯了一个错误,请告诉我,这里唯一能看到的问题是宽度装订。

我已经尝试使用childrenRect,但是不起作用

width: childrenRect.width
height: childrenRect.height

注意:stackpanel允许您将一个项目接一个接一个地堆叠,您可以将方向设置为水平或垂直,这样在qt的列和行中就可以了,我已经做到了。
/> 纵向一: a vertical stack panel
水平一:
a horizontal stack panel

1 个答案:

答案 0 :(得分:4)

通过设置Grid的数量,您可以使用columns轻松地做到这一点。 如果需要单独的组件,可以使用以下命令创建StackPanel.qml:

import QtQuick 2.0

Grid {
    property int orientation: Qt.Horizontal
    columns: orientation === Qt.Horizontal ? -1 : 1
}

QML StackPanel

如果要使用可滚动对象,也可以将ListViewObjectModel模型一起使用。 ListView具有orientation属性。