我想使用繼承QAbstractListModel的類來填充QML ListView。到目前爲止,我管理這個使用Qt文檔here打造的 「化QAbstractItemModel子類」 部分:使用QQmlContext訪問嵌套的ListView
的main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "gamemodel.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
GameModel model; //A class similar to AnimalModel in Qt Documentation.
//It contains a QList of Objects, each having 2 QString
//members (title and genre).
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
model.readFile("c:/somePath/XML_G.xml"); //Initializing GameModel QList member
//using an XML file
QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("myModel", &model);
return app.exec();
}
main.qml
import QtQuick 2.5
import QtQuick.Window 2.2
Window
{
id: win
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ListView
{
id: myList
width: parent.width
height: 50
clip: true
spacing: 5
orientation: ListView.Horizontal
model: myModel
delegate:
Rectangle
{
width: 150
height: 20
color: "#2255ff"
Text
{
text: gameTitle + " " + genre
}
}
}
}
到目前爲止,我的代碼工作。但是,如果我試圖改變我的main.qml文件是這樣的:
import QtQuick 2.5
import QtQuick.Window 2.2
Window
{
id: win
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Item //ListView is now nested in this Item
{
ListView
{
id: myList
width: parent.width
height: 50
clip: true
spacing: 5
orientation: ListView.Horizontal
model: myModel
delegate:
Rectangle
{
width: 150
height: 20
color: "#2255ff"
Text
{
text: gameTitle + " " + genre
}
}
}
}
}
我最終是無法設置使用ctxt-> setContextProperty( 「基於myModel」 &模型)我的模型。從我從Qt文檔中可以收集到的信息(儘管我很可能是錯誤的),QQmlContext就像是QML文件的作用域。思考的是,我試圖改變這樣的:
QQmlContext *ctxt = engine.rootContext();
這樣:
QQmlContext *ctxt = engine.rootContext()->findChild<QQmlContext*>("list");
以及設置我的貨品的對象名屬性設置爲 「列表」。很明顯,那次失敗了,而且也造成了一次崩潰。由於我對QML的經驗僅限於Qt Docs,因此我找不到解決方法。是否可以使用QQmlContext的解決方案,還是我必須使用QObject?如果是這樣,那麼QObject相當於ctxt-> setContextProperty(「myModel」,& model)是什麼?
嘗試做QQmlContext * ctxt = engine.rootContext(); ctxt-> setContextProperty(「myModel」,&model);在engine.load()之前。例如,在加載視圖之前定義模型之後。 – arynaq
我上面的代碼正常工作。我想要做的是訪問一個ListView嵌套在另一個項目中,這是我目前卡住的地方。 – SASUPERNOVA