2013-06-26 9 views
10

पर कोड पुन: उपयोग करने मैं QML कोड के इस टुकड़े है:कैसे 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 प्रोग्रामिंग की सर्वोत्तम प्रथाओं, कैसे आम तत्वों की डुप्लीकेट विशेषताओं से बचने के लिए कोड का पुन: उपयोग के लिए? जैसे, उपर्युक्त उदाहरण में, पंक्तियों से बचें "रिक्ति: units.gu (4)"।

उत्तर

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 
       { 

       } 
      } 
} 

संपादित करें:

एक एकल फाइल में यह कर (के रूप में टिप्पणी में पूछा) के लिए आप Loader तत्व के साथ Qml Component तत्व का उपयोग कर सकते हैं:

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 

     } 
    } 
+0

दिलचस्प। और एक ही फाइल में ऐसा कैसे करें? –

+1

@ayr_ton मैंने एक संपादन किया है। चेक। –

 संबंधित मुद्दे