【问题标题】:How to expose a C++ Model to QML如何将 C++ 模型公开给 QML
【发布时间】:2012-08-04 05:55:35
【问题描述】:

我正在编写一个 QML+Qt 应用程序。 我定义了一个这样的类:

class MainClass : public QObject
{
    Q_OBJECT

public:
    rosterItemModel m_rosterItemModel;
.
.
.
}

rosterItemModel 模型是从 QAbstractListModel 派生的一个类。 我使用这个函数将 MainClass 暴露给 qml 部分:

qmlRegisterType<MainClass>("CPPIntegrate", 1, 0, "MainClass");

现在我想将此模型(m_rosterItemModel)从 MainClass 分配给 QML 中 ListView 的模型属性。 我尝试了以下方法,但都没有帮助:(

  • 我尝试使用 Q_PROPERTY 将 m_rosterItemModel 声明为 PROPERTY。 我不能这样做,因为它说 QAbstractListModel 不是 可复制。
  • 我试图在 qml 文件中使用一个指向 m_rosterItemModel 的指针 MainClass 中的 Q_INVOKABLE 函数。但这也无济于事。

有人可以帮我吗?

【问题讨论】:

    标签: qt qml qt-quick


    【解决方案1】:

    不应该有任何必要的元类型注册。 您只需要调用 setContextProperty 并通过 pointer 传递模型:

    QQmlContext* context = view->rootContext(); //view is the QDeclarativeView
    context->setContextProperty( "_rosterItemModel", &mainClassInstance->m_rosterItemModel );
    

    在 QML 中使用它:

    model: _rosterItemModel
    

    通过指针很重要,因为 QObject 不是可复制构造的,并且复制它们无论如何都会破坏它们的语义(因为它们具有“身份”)。

    直接注册模型的替代方法是注册主类的实例并使用 Q_INVOKABLE。在 MainClass 中:

    Q_INVOKABLE RosterItemModel* rosterItemModel() const;
    

    注册一个mainClass的实例(mainClassInstance再次假设为一个指针):

    context->setContextProperty( "_mainInstance", mainClassInstance );
    

    在 QML 中:

    model: _mainInstance.rosterItemModel()
    

    【讨论】:

    • 我使用 qmlRegisterType 将 MainClass 注册到 QML,以便通过创建 MainClass{id:mc} 之类的实例在 QML 中轻松使用 MainClass 信号和插槽。反正 。谢谢你:)
    • 从经验看来,在第二种情况下也需要注册模型类:qmlRegisterType&lt;rosterItemModel&gt;("CPPIntegrate", 1, 0, "MainClass"); 此外,使用const 修饰符似乎会破坏互操作。最后一个古怪的地方是始终在标头的 Q_PROPERTY 和 Q_INVOKABLE 声明中引用具有完整命名空间限定的类。此外,如果尝试返回某个基类(如 QAbstractItemModel)指针,则互操作性将再次失败,请注意。
    • 如何获取mainClassInstance?
    • 从 C++ 向 QML 公开属性是可以的,但是为什么“使用 MainClass 中的 Q_INVOKABLE 函数在 qml 文件中获取指向 m_rosterItemModel 的指针”失败?
    • 既然 mainClassInstance 也是一个 QObject,为什么不在第二个示例中也通过指针传递它?
    猜你喜欢
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多