如何将具有自定义 属性 的组件移动到 QML 中的单独文件

How to move a component with a custom property to a separate file in QML

我有一个语言选择列表的代表。列表中的每个项目都包含一个图标和文本。 我想将组件定义移动到不同的文件并提供当前由 IMGDIR 定义的字符串作为 属性。

只需将下面的整个文本移动到单独的 LandDelegate.qml 文件并将其包含为:

LangDelegate { id: langDlg }

无效。

下面是组件的声明。

Component {
    id: langDlg
    Item {
        id: wrapper

        width: langView.width
        height: langImg.height+10*2

        Rectangle {
            id: background
            x: 2; y: 2; width: parent.width - x*2; height: parent.height - y*2
            color: "lightgrey"
            border.color: "orange"
            radius: 5
        }

        states: State {
            name: "Current"
            when: wrapper.ListView.isCurrentItem
            PropertyChanges { target: wrapper; x: 20 }
        }
        transitions: Transition {
            NumberAnimation { properties: "x"; duration: 200 }
        }
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            onEntered: { wrapper.ListView.view.currentIndex = index; }
            onClicked: { wrapper.ListView.view.currentIndex = index; langSelect.visible = false; docView.visible  = true }
        }

        Row {
            id: topLayout
            x: 10; y: 10; height: langImg.height + 10*2; width: parent.width
            spacing: 10

            Image {
                id: langImg
                //width: 50; height: 50
                source: IMGDIR+licon
            }

            Column {
                width: background.width - langImg.width - 20; height: langImg.height
                spacing: 5

                Text {
                    text: lname
                    font.bold: true; font.pointSize: 16
                }
            }
        }
    }
}

据我所知和 according 文档,

The Component type essentially allows QML components to be defined inline, within a QML document, rather than as a separate QML file.

Here我们有更多关于这个问题的信息,

A component is an instantiable QML definition, typically contained in a .qml file. For instance, a Button component may be defined in Button.qml.

因此,在您的情况下,您的 LangDelegate.qml 文件不需要根 Component 元素。使用 Item 而不是 Component.

示例:

LangDelegate.qml

import QtQuick 2.0

Item {
    id: langDlg

    width: 100
    height: 100

    Rectangle {
        id: background
        x: 2; y: 2; width: parent.width - x*2; height: parent.height - y*2
        color: "lightgrey"
        border.color: "orange"
        radius: 5
    }
}

main.qml

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    LangDelegate { id: langDlg }
}