使用QQMLContext访问嵌套ListView
Accessing nested ListView with QQmlContext
我正在尝试使用继承qabstractlistmodel的类填充QML ListView。到目前为止,我设法在此处使用QT文档来创建它,在" 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-> setContextProperty(" mymodel",&amp; model);。从QT文档中我几乎无法收集的东西(尽管我很可能是错误的),QQMLContext的作用就像QML文件的范围。想到,我尝试更改它:
QQmlContext *ctxt = engine.rootContext();
:
QQmlContext *ctxt = engine.rootContext()->findChild<QQmlContext*>("list");
以及将我的项目的 objectName 属性设置为"列表"。显然,这失败了,这也导致了崩溃。由于我在QML的经验仅限于QT文档,因此我在找到解决方法方面没有成功。使用QQMLContext的解决方案是否可能是可能的,还是我必须使用Qobject?如果是这样, ctxt-> setContextProperty(" mymodel",&amp; model) be be be
setContextProperty()
调用的第一个参数基本上是对象的"标识符",就像QML侧的id
属性一样。
您需要在QML中访问它之前将其设置,否则在使用时未知。
因此,您不需要任何其他电话,但是您需要在加载需要它的QML之前进行此操作。
只需在main.cpp
engine.load(...)
行之前移动它好吧,显然我的问题在我的QML文件中。在我的代码中,我设置了这样的listView:
width: parent.width
但是,当我添加一个项目作为我的listView的父时,我忘了为项目设置初始宽度,从而将ListView的宽度转换为0。。
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 如何在嵌套类中正确使用友元声明?
- 使用QQMLContext访问嵌套ListView