2014-10-18 61 views
0

我有兩個幾乎相同的qml文件。我列出了他們中的一個在這裏,與註釋行顯示的另一個的區別:2個相同的ListView與代表內部的小差異

// MessageView.qml; diff. to ThreadView.qml is shown with comment lines 
import QtQuick 2.0 

Item { 
    property var model 
    property var selectedThread: threadsList.currentItem.myThread 
    property alias spacing: threadsList.spacing 
    signal activated(var selectedThread) 
    id: root 

    ListView { 
     anchors.fill: parent 

     id: threadsList 
     model: root.model 
     delegate: Rectangle { 
      property var myThread: message // the other file contains `thread` instead of `message` here 

      color: threadsList.currentItem == this ? "cyan" 
                : index % 2 ? "lightblue" : "lightsteelblue" 
      width: parent.width 
      height: ti.implicitHeight 

      MessageItem { // the other file contains `ThreadItem` instead of `MessageItem` here 
       id: ti 
       anchors.left: parent.left 
       anchors.right: parent.right 
       anchors.verticalCenter: parent.verticalCenter 
       anchors.margins: 8 
      } 

      MouseArea { 
       anchors.fill: parent 
       onClicked: { 
        threadsList.currentIndex = index 
        activated(root.selectedThread) 
       } 
      } 
     } 
    } 
} 

這些2個組件意在與委託外觀細微的差別看起來相似的列表視圖。如何將這兩個文件合併爲一個以便能夠像這樣使用它們?

MerdedView { 
    MessageItem { 
     // more property customization 
    } 
} 
MerdedView { 
    ThreadItem { 
     // more property customization 
    } 
} 

回答

1

委託內部只有很小的差異,所以您需要提取公共代碼。例如,MerdedViewDelegate.qml

Rectangle { 
    id: viewItem 

    property var myThread 
    //other properties: color, width, height, ... 

    MouseArea { 
     anchors.fill: parent 
     onClicked: { 
      //use the attached property in ListView 
      viewItem.ListView.view.currentIndex = index 
     } 
    } 
} 

然後創建MergedView.qml就像你MessageView.qml,除了委託現改爲別名屬性:

//MergedView.qml 
Item { 
    property alias delegate: threadsList.delegate 
    //other properties 

    ListView { 
     anchors.fill: parent 

     id: threadsList 
     model: root.model 
    } 
} 

最後,你可以寫你的QML是這樣的:

MergedView { 
    delegate: MergedViewDelegate{ 
     myThread: message //or something similar 
     MessageItem { /* ... */ } 
    } 
} 

MergedView { 
    delegate: MergedViewDelegate{ 
     myThread: thread 
     ThreadItem { /* ... */ } 
    } 
} 
+0

謝謝。我也使用Loader來擺脫單獨的MergedViewDelegate – sshilovsky 2014-10-25 23:14:11