我正在尝试使用继承QAbstractListModel的类填充QML ListView。到目前为止,我设法使用QT文档here在“QAbstractItemModel子类”部分下创建了这个:
的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-&gt; setContextProperty(“myModel”,&amp; model);来设置我的模型。从我从Qt文档中收集到的很少(虽然我很可能是错误的),QQmlContext就像QML文件的作用域。想到这一点,我试着改变这个:
QQmlContext *ctxt = engine.rootContext();
到此:
QQmlContext *ctxt = engine.rootContext()->findChild<QQmlContext*>("list");
将Item的 objectName 属性设置为“list”。显然,失败了,它也导致了崩溃。由于我使用QML的经验仅限于Qt文档,因此我找不到解决方法。是否可以使用QQmlContext解决方案,还是必须使用QObject?如果是这样,那么QObject相当于 ctxt-&gt; setContextProperty(“myModel”,&amp; model)会是什么?
答案 0 :(得分:0)
setContextProperty()
电话的第一个参数基本上是&#34;标识符&#34;对象,就像QML端的id
属性一样。
您需要在使用QML访问它之前设置它,否则在使用时它是未知的。
所以你不需要任何其他电话,但在加载需要它的QML之前你需要这样做。
只需在engine.load(...)
main.cpp
行之前移动它
答案 1 :(得分:0)
好的,显然我的问题出在我的QML文件中。在我的代码中,我设置了ListView,如下所示:
width: parent.width
但是,当我添加一个Item作为ListView的父级时,我忘了为我的Item设置一个初始宽度,从而将ListView的宽度变为0.在我为我的Item设置初始宽度后,所有内容再次按预期工作。