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.
This is my QML code:
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);
}
}
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
And that's for Quick 1.1
MainModel(0x7fffe58182f0)
undefined
QDeclarativeVisualDataModelData(0x2372ea0)
QVariant(MiniModel*)
QVariant(MiniModel*)
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. 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. My code example should be compilable on GNU/Linux x64
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; }
There's a working example too: examples/quick/modelviews/abstractitemmodel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With