首页 文章

如何在QML上重用代码

提问于
浏览
10

我有这条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)” .

1 回答

  • 10

    将代码放在单独的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
    
           }
        }
    

相关问题