在 Qt 5.0 中向 QML 公开 QAbstractListModel 元素属性 [英] Expose QAbstractListModel element properties to QML in Qt 5.0

查看:65
本文介绍了在 Qt 5.0 中向 QML 公开 QAbstractListModel 元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直松散地关注 Christophe Dumez 的博客 获取自定义 QAbstractListModel 类以将数据公开到 QML (QtQuick2) 接口 (QtQuick2ApplicationViewer).但是,由于我使用的是 Qt 5.0.0(和 MSVC2012),因此他的文章中有些部分不适用.例如,ListModel 构造函数不再需要调用 setRoleNames(),因为 setRoleNames() 已在 Qt 5 中折旧.

I've been loosely following the article on Christophe Dumez's blog to get a custom QAbstractListModel class to expose the data to a QML (QtQuick2) interface (QtQuick2ApplicationViewer). However, since I'm using Qt 5.0.0 (and MSVC2012), there are some parts of his article that don't apply. For example, the ListModel constructor no longer has to call setRoleNames(), because setRoleNames() has been depreciated in Qt 5.

ListModel::ListModel(ListItem* prototype, QObject *parent) :
    QAbstractListModel(parent), m_prototype(prototype)
{
  setRoleNames(m_prototype->roleNames());
}

据我了解,从 QAbstractListModel 继承的类必须只定义 roleNames(),因为它在 Qt 5 中已更改为纯虚函数.所以在他的示例中,我只是注释掉 setRoleNames(m_prototype->roleNames()); 在构造函数中,一切都应该正常工作.对吗?

It is my understanding that the class that inherits from QAbstractListModel must only define roleNames(), as it has been changed to be a purely virtual function in Qt 5. So in his example, I simply comment out setRoleNames(m_prototype->roleNames()); in the constructor and everything should work. Right?

但是,当通过 QML 访问时,所有定义的角色都是未定义的.我可以用这个检查 C++ 中的名称:

But instead, all of the defined roles are undefined, when accessed through QML. I can check the names in C++ with this:

QHash<int, QByteArray> mynames = model->find("Elephant")->roleNames();
qDebug() << "Model: " << mynames;

在这种情况下,大象对象的角色名称按预期打印.

In this case, the role names for the Elephant object print as expected.

我的假设是否正确,或者我是否需要做其他事情来获取 QAbstractListModel 对象以与 QML2 共享列表元素属性?这似乎是一个愚蠢的问题,但 Qt5 文档现在非常糟糕,我无法弄清楚.

Are my assumptions correct, or do I need to do something else to get a QAbstractListModel object to share list element properties with QML2? This seems like a stupid question, but the Qt5 docs are so broken right now, I can't figure it out.

谢谢!

推荐答案

您需要重新实现 QAbstractListModel::roleNames() const 方法,您的角色会自动在 QML 中注册.

You need to reimplement QAbstractListModel::roleNames() const method and your roles get registered in QML automatically.

examples/quick/modelviews/abstractitemmodel 中有一个将基于 QAbstractListModel 的模型暴露给 QML 的工作示例.

There's a working example of an exposing QAbstractListModel-based model to QML at examples/quick/modelviews/abstractitemmodel.

您还可以考虑使用 QQmlListProperty.

这篇关于在 Qt 5.0 中向 QML 公开 QAbstractListModel 元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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