想要实现使用ListView运行时动态载入Item,需要两个步骤:
- 动态生成Item
- 将动态生成的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"
}