QML:使用ListView运行时动态载入Item

28 篇文章 4 订阅

想要实现使用ListView运行时动态载入Item,需要两个步骤:

  1. 动态生成Item
  2. 将动态生成的Item插入到ListView的model中

对于这两个步骤,前者可以使用createComponent和Component.createObject实现,后者可以使用ObjectModel实现,详细内容可见官方文档:
http://doc.qt.io/qt-5.9/qml-qtqml-qt.html#createComponent-method
http://doc.qt.io/qt-5.9/qml-qtqml-models-objectmodel.html

代码如下:
main.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QVariantMap>
#include <QStringList>

int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    QStringList pageList;
    pageList << "RedPage.qml" << "GreenPage.qml" << "BluePage.qml";
    engine.rootContext()->setContextProperty("pageList", QVariant::fromValue(pageList));

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

qml文件:

// main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQml.Models 2.1

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

    ObjectModel {
        id: pageModel
    }

    ListView {
        id: view
        anchors.fill: parent
        orientation: ListView.Horizontal
        snapMode: ListView.SnapOneItem
        model: pageModel
    }

    Component.onCompleted: {
        for (var i in pageList) {
            console.log(pageList[i]);
            var component = Qt.createComponent(pageList[i]);
            if (component.status == Component.Ready) {
                var page = component.createObject(pageModel, { parent: null });
                pageModel.append(page);
            }
        }
    }
}

// RedPage.qml
import QtQuick 2.0

Rectangle {
    width: 640
    height: 480
    color: "red"
}

// GreenPage.qml
import QtQuick 2.0

Rectangle {
    width: 640
    height: 480
    color: "green"
}

// BluePage.qml
import QtQuick 2.0

Rectangle {
    width: 640
    height: 480
    color: "blue"
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值