Loader 创建的组件的绑定属性

Binding properties of the component created by the Loader

我要根据条件加载主window:

Loader {
    source: blocky ? "BlockyMainWindow.qml" : "RoundyMainWindow.qml"
}

但是要绑定的属性是一样的:width/height, anchors, transform.

只有当所有内容都写入 onLoaded 处理程序时,它才有效。此外,您必须编写两次:第一次执行 Qt.binding,第二次仅分配值,因为如果不更改某些值,绑定将无法启动。

属性:

    width: ContentOrientation.rotated ? parent.height : parent.width
    height: ContentOrientation.rotated ? parent.width : parent.height

    anchors.left: parent.left
    anchors.top: ContentOrientation.rotated ? parent.bottom : parent.top
    transform: Rotation { origin.x: 0; origin.y: 0; angle: ContentOrientation.rotated ? -90 : 0 }

如何让它变得简单?

您或许可以将那些 属性 绑定移动到 Loader 本身:

Loader {
    source: blocky ? "BlockyMainWindow.qml" : "RoundyMainWindow.qml"

    width: ContentOrientation.rotated ? parent.height : parent.width
    height: ContentOrientation.rotated ? parent.width : parent.height
    // etc.
}

例如:

import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    id: window
    visible: true

    Component {
        id: blockyComponent

        Rectangle {
            color: "red"

            Text {
                text: "Blocky"
            }
        }
    }

    Component {
        id: roundedComponent

        Rectangle {
            color: "green"
            radius: 20

            Text {
                text: "Rounded"
            }
        }
    }

    Loader {
        sourceComponent: loaderType.checked ? blockyComponent : roundedComponent
        anchors.fill: parent
        rotation: 90
    }

    Switch {
        id: loaderType
    }
}

有关详细信息,请参阅 Loader sizing behavior