QML:使用ListView運行時動態載入Item

想要實現使用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 {
        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(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"
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章