【问题标题】:How to move a component with a custom property to a separate file in QML如何将具有自定义属性的组件移动到 QML 中的单独文件
【发布时间】:2016-06-23 08:25:29
【问题描述】:

我有一个语言选择列表的代表。列表中的每个项目都包含一个图标和文本。 我想将组件定义移动到不同的文件中,并将当前由 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
                }
            }
        }
    }
}

【问题讨论】:

  • @Mitch 不,不起作用。无论如何感谢您的贡献:-)

标签: qt qml qtquick2 qqmlcomponent


【解决方案1】:

据我所知,according 到文档中,

Component 类型本质上允许定义 QML 组件 内联,在 QML 文档中,而不是作为单独的 QML 文件。

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

组件是一个可实例化的 QML 定义,通常包含在 .qml 文件。例如,一个 Button 组件可以定义在 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
    }
}

ma​​in.qml

import QtQuick 2.5
import QtQuick.Window 2.2

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

    LangDelegate { id: langDlg }
}

【讨论】:

  • 额外的langDlg 项目可以省略。 :)
  • 非常感谢您的解释。似乎确实很容易。 P.S.:不幸的是,我放弃了 QML 并再次切换到 C++。无论如何,任何不平凡的快速应用程序都需要接触 C++。就我而言,我在模型和过滤器上失败了
  • @ValentinHeinitz 我同意你的看法。 QML 应用程序通常需要 C++ 来完成复杂的任务。无论如何,谢谢你!快乐编码:)
猜你喜欢
  • 2010-12-06
  • 2018-02-12
  • 2011-06-29
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 2016-12-21
相关资源
最近更新 更多