11

我有这段 QML 代码:

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

QML编程的最佳实践,如何重用代码以避免常见元素的重复属性?比如,在上面的例子中,避免行“spacing:units.gu(4)”。

4

1 回答 1

11

将您的代码放在单独的 qml 文件中,并将该文件名用作元素。例如。

// 文件 MyCustomRow.qml

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

然后在您的其他 qml 文件中:

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

       }
       MyCustomRow{

       }
       MyCustomRow{

       }
       MyCustomRow{

       }
    }

事实上,你可以使用中继器:

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

           Repeater
           {
               model : 5
               MyCustomRow
               {

               }
           }
}

编辑 :

要在单个文件中执行此操作(如评论中所述),您可以使用 Qml Component元素和Loader元素:

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

       }
    }
于 2013-06-26T19:22:59.760 回答