【问题标题】:How to reuse code at QML如何在 QML 中重用代码
【发布时间】:2013-06-23 19:07:21
【问题描述】:

我有这段 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)”。

【问题讨论】:

    标签: qt qml


    【解决方案1】:

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

    【讨论】:

    • 有趣。以及如何在同一个文件中做到这一点?
    • @amit 我应该如何重用 qml 文件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2015-08-07
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多