简体   繁体   中英

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

As a newbie to qml/qt programming, I would like to solve following issue;

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
       }
    }
}

I want to achieve that Rectangle Component which is written under of comment lines in MyComponent2.qml have some properties which will be predefined (like anchors.top: parent.top) in MyComponent1.qml.

For this example: "anchors.top: parent.top" is written 3 times within code in MyComponent2.qml.

Can we define it one time in MyComponent1.qml and apply it to all of 3 predefined Rectangle Components in MyComponent2.qml?

My goal is to increase the reusability of the code.

Thank you all in advance.

Use this property alias inside MyComponent1:

myRect : rectId

And use this inside MyComponent2 to redefine anchors of rectangle:

myRect.anchors.top : parent.top

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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