繁体   English   中英

将属性分配给可以在 QML 组件内定义的可能组件

[英]Assign properties to possible components that can be defined inside a QML component

作为 qml/qt 编程的新手,我想解决以下问题;

MyComponent1.qml:

import QtQuick 2.0

Rectangle {
    width: 100
    height: 100
    border.color: "black"
    border.width: 5

    Text {
         height: 20
         anchors.bottom: parent.bottom
    }
}

MyComponent2.qml

import QtQuick 2.0
Rectangle {
    MyComponent1{   
       //here can be added any kind of component Rectangle or other components
       Rectangle {
         anchors.top: parent.top
       }
    }
    MyComponent1{   
       //here can be added any kind of component Rectangle or other components
       Rectangle {
         anchors.top: parent.top
       }
    }
    MyComponent1{   
       //here can be added any kind of component Rectangle or other components
       Rectangle {
         anchors.top: parent.top
       }
    }
}

我想实现写在 MyComponent2.qml 中的注释行下的矩形组件,它有一些将在 MyComponent1.qml 中预定义的属性(如 anchors.top: parent.top)。

对于此示例:“anchors.top: parent.top”在 MyComponent2.qml 的代码中被写入 3 次。

我们可以在 MyComponent1.qml 中定义一次并将其应用于 MyComponent2.qml 中的所有 3 个预定义矩形组件吗?

我的目标是增加代码的可重用性。

谢谢大家。

在 MyComponent1 中使用此属性别名:

myRect : rectId

并在 MyComponent2 中使用它来重新定义矩形的锚点:

myRect.anchors.top : parent.top

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM