簡體   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