如何在QML中重用代码

12

我有这段 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编程的最佳实践,如何重用代码以避免常见元素的重复属性?例如,在上面的示例中,避免在Rows中使用"spacing: units.gu(4)"。

About QML编程的最佳实践,如何重复使用代码以避免常见元素的重复属性?例如,对于上面的示例,避免在Rows中使用“spacing: units.gu(4)”。
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

       }
    }

有趣。那么如何在同一个文件中实现呢? - ayr-ton
@amit 我应该如何重复使用 QML 文件? - mohsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接