Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse code at QML

Tags:

qt

qml

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)".

like image 797
ayr-ton Avatar asked Jun 26 '13 14:06

ayr-ton


1 Answers

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

       }
    }
like image 182
Amit Tomar Avatar answered Oct 02 '22 12:10

Amit Tomar