-->

How to reuse code at QML

2020-08-18 17:12发布

问题:

I have this piece of QML code:

   Column {
       spacing: units.gu(2)
       anchors {
           fill: parent
           centerIn: parent
       }
       Row {
           spacing: units.gu(4)
           ...
       }
       Row {
           spacing: units.gu(4)
           ...
       }
       Row {
           spacing: units.gu(4)
           ...
       }
       Row {
           spacing: units.gu(4)
           ...
       }
    }

About best practices of QML programming, how to reuse code to avoid duplicate attributes of common elements? like, in the above example, avoid Rows "spacing: units.gu(4)".

回答1:

Put your code in a separate qml file, and use that file name as an element. eg.

// File MyCustomRow.qml

Row {
       spacing: units.gu(4)
       ...
    }

Then in your other qml file :

   Column {
       spacing: units.gu(2)
       anchors {
           fill: parent
           centerIn: parent
       }
       MyCustomRow{

       }
       MyCustomRow{

       }
       MyCustomRow{

       }
       MyCustomRow{

       }
    }

Infact you could use a repeater :

Column 
{
           spacing: units.gu(2)
           anchors 
           {
               fill: parent
               centerIn: parent
           }

           Repeater
           {
               model : 5
               MyCustomRow
               {

               }
           }
}

Edit :

For doing it in a single file(as asked in the comment) you can use Qml Component element along with Loader element:

Column {
       spacing: units.gu(2)
       anchors {
           fill: parent
           centerIn: parent
       }


       Component 
       {
         id :  myCustomRow
         Row 
         {
            spacing: units.gu(4)
            ...
         }
       }

       Loader {
       sourceComponent : myCustomRow

       }
       Loader {
       sourceComponent : myCustomRow

       }
       Loader {
       sourceComponent : myCustomRow

       }
       Loader {
       sourceComponent : myCustomRow

       }
    }


标签: qt qml