Qt5和Qt 4.8中的模型和角色 [英] Models and roles in Qt5 and Qt 4.8

查看:198
本文介绍了Qt5和Qt 4.8中的模型和角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我想和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

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中的模型和角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆