本页内容

加载占位符数据

Qt Quick Designer 支持视图、模型和委托,因此当您添加 Grid View、List View 或 Path View 组件时,ListModel 和委托组件会自动添加。

然而,应用程序中上下文信息的缺失却带来了一定挑战。在 C++ 中定义的特定模型便是最明显的例子。通常,上下文中会缺少一些简单的属性,这些属性要么在 C++ 中定义,要么在其他组件文件中定义。一个典型的例子是使用其父组件属性的组件,例如parent.width

使用占位模型

如果您在“2D ”视图中打开一个引用了 C++ 模型的文件,会发现其中没有任何内容。如果您从互联网获取模型中的数据,则无法对其进行控制。为了获得可靠的数据,请使用占位数据

例如,以下代码片段描述了文件example.qml ,该文件包含一个ListView ,而该文件又指定了一个 C++ 模型:

ListView {
    model: dataModel
    delegate: ContactDelegate {
        name: name
    }
}

在项目的根目录下创建一个名为dummydata的目录,以确保该目录不会被部署到设备上。在dummydata 目录中,创建一个文件(.qml ),其名称应与model 的值相同:

qml/exampleapp/example.qml
dummydata/dataModel.qml

然后创建包含模拟数据的dataModel.qml 文件:

import QtQuick 2.0

ListModel {
     ListElement {
         name: "Ariane"
     }
     ListElement {
         name: "Bella"
     }
     ListElement {
         name: "Corinna"
     }
}

创建模拟上下文

以下示例展示了一种常见模式:

Item {
    width: parent.width
    height: parent.height
}

此方法在应用程序中运行良好,但2D 视图会显示一个大小为零的组件。由于缺少上下文,已打开文件的父上下文并不存在。为解决上下文缺失的问题,引入了虚拟上下文的概念。如果您在dummydata/context 目录中放置一个与应用程序同名的文件(此处为example.qml ),即可模拟父上下文:

import QtQuick 2.0
import QmlDesigner 1.0

DummyContextObject {
    parent: Item {
        width: 640
        height: 300
    }
}

另请参阅 《如何设计Qt Quick 用户界面》Qt Quick 用户界面设计》以及 设计Qt Quick 用户界面

Copyright © The Qt Company Ltd. and other contributors. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.