如何制作一些可重用的QML对象,它可以注入另一个QML对象?

kua*_*yui 6 qt qml qqmlcomponent

如何制作一些可重用的 QML 对象,它可以注入另一个对象?

我曾经尝试过使用Component& Loader,但似乎不是我想要的。(仍然封装了整个QML类型,缺乏弹性,难以复用)

使用示例:

Card.qml

import QtQuick 2.0
import QtQuick.Layouts 1.3

Rectangle {
    default property var innerObject
    property string titleText: "[Hello Untitled Title]"
    id: root
    color: "#fff"
    ColumnLayout {
        anchors.fill: parent
        Rectangle {
            id: header
            height: 10
            width: parent.width
            color: "#666"
            RowLayout {
                Text { text: titleText; color: "#fff" }
            }
        }

        // How to inject innerObject in here ?

    }
}
Run Code Online (Sandbox Code Playgroud)

main.qml

import QtQuick 2.0
import QtQuick.Layouts 1.3

Card {
    titleText: "Image Information"
    ColumnLayout { /* .......*/ }   // innerObject
}

Card {
    titleText: "Image Viewer"
    Rectangle { /* .......*/ }      // innerObject
}
Run Code Online (Sandbox Code Playgroud)

Tee*_*kko 4

我链接的答案是这样的:

主.qml

Card {
    titleText: "Image Viewer"
    innerObject: Rectangle {
        Component.onCompleted: {
            console.log(parent.objectName)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

卡.qml

Rectangle {
    property string titleText: "[Hello Untitled Title]"

    default property alias innerObject : innercolumn.children


    id: root
    color: "#fff"
    ColumnLayout {
        id: innercolumn
        objectName: "column"
        anchors.fill: parent
        Rectangle {
            id: header
            height: 10
            width: parent.width
            color: "#666"
            RowLayout {
                Text { text: titleText; color: "#fff" }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 其实根本不需要占位符项,直接 `default property alias insideObject:innerColumn.children` 即可 (2认同)