问题描述
今天我想和QtQuick2一起玩.因此,我已经开始将非常简单的Qt Quick1应用程序移植到Quick2.这个程序使用一些模型.而且在Qt5中,模型无法正常运行:我无法使用角色访问数据.
Today I wanted to play with QtQuick2 a little bit. So I have started to port very simple Qt Quick1 app to Quick2. This app uses some models. And in Qt5 models are not working as I expect: I can't access data using roles.
这是我的QML代码:
import QtQuick 2.0
Rectangle {
width: 800
height: 360
ListView {
model: mainModel
spacing: 5
anchors.fill: parent
orientation: ListView.Vertical
delegate: Text {
text: "1"
Component.onCompleted: {
console.log(mainModel);
console.log(mainModel.roles() );
console.log(model);
console.log(model.homm); // `homm` is my roleName
console.log(homm);
}
}
在Qt4.8中,我能够使用roleName
语法获取数据(在此QML中,我的roleName = homm
),但在Qt5中,我无法.那就是在控制台中写的:
In Qt4.8 I was able to get data using roleName
syntax (in this QML my roleName=homm
) but in Qt5 I can't. That's what is written in console:
MainModel(0x7fff08beff80)
homm,wtf
QQuickVDMAbstractItemModelData(0x23c96e0)
undefined
file:///media/disk/kakadu/prog/qt/quick2test/qml/quick2test/main.qml:20: ReferenceError: homm is not defined
那是针对Quick 1.1的
And that's for Quick 1.1
MainModel(0x7fffe58182f0)
undefined
QDeclarativeVisualDataModelData(0x2372ea0)
QVariant(MiniModel*)
QVariant(MiniModel*)
您可以看到使用角色访问数据的工作正常.我已经为您创建了测试应用程序:对于Qt5 和对于Qt 4.8 .希望您能帮助我找到问题的核心.
As you can see accessing data using roles work as expected. I have created test apps for you:for Qt5 and for Qt 4.8. I hope you will help me to find the heart of matter.
P.S.我在Qt5版本中做了一些更改.在Qt5中,方法setRoleNames()
已过时,建议覆盖roleNames()
.我已经完成了此覆盖.
P.S. I have made some changes in Qt5 version. In Qt5 method setRoleNames()
is obsolete and overriding of roleNames()
is recommended. I have done this overriding.
P.P.S.我的代码示例应该可以在GNU/Linux x64上编译
P.P.S. My code example should be compilable on GNU/Linux x64
推荐答案
我在您的代码中发现了一个错误. roleNames()
是常量方法.这是一段工作代码:
I found a mistake in your code. roleNames()
is constant method. Here's a working line of code:
virtual QHash<int, QByteArray> roleNames() const { return _roles; }
也有一个有效的示例:examples/quick/modelviews/abstractitemmodel.
There's a working example too: examples/quick/modelviews/abstractitemmodel.
这篇关于Qt5和Qt 4.8中的模型和角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!