0

我有两个几乎相同的 qml 文件。我在这里列出其中一个,另一个与注释行显示的差异:

// 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
    }
}
4

1 回答 1

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 { /* ... */ }
    }
}
于 2014-10-25T13:33:22.190 回答