QML:使⽤ListView运⾏时动态载⼊Item 想要实现使⽤ListView运⾏时动态载⼊Item,需要两个步骤:
1. 动态⽣成Item
2. 将动态⽣成的Item插⼊到ListView的model中
代码如下:
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.load(QUrl(QStringLiteral("qrc:/main.qml")));
Objects().isEmpty())
return-1;
();
}
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
}
for (var i in pageList) {
console.log(pageList[i]);
var component = Qt.createComponent(pageList[i]);
if (component.status == Component.Ready) {
var page = ateObject(pageModel, { parent: null });                pageModel.append(page);
qt listview}
}
}
}
// 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"
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。