问题描述
我正在编写一个 QML+Qt 应用程序.我定义了一个这样的类:
I'm writing a QML+Qt application .I defined a class like this :
class MainClass : public QObject
{
Q_OBJECT
public:
rosterItemModel m_rosterItemModel;
.
.
.
}
rosterItemModel 模型是从 QAbstractListModel 派生的一个类.我使用这个函数将 MainClass 暴露给 qml 部分:
rosterItemModel model is a class derived from QAbstractListModel.I exposed MainClass to qml part using this function :
qmlRegisterType<MainClass>("CPPIntegrate", 1, 0, "MainClass");
现在我想将此模型(m_rosterItemModel)从 MainClass 分配给 QML 中 ListView 的模型属性.我尝试了以下方法,但都没有帮助:(
Now I want to assign this model(m_rosterItemModel) from MainClass to model property of a ListView in QML.I tried the following ways but none of them were helpful :(
- 我尝试使用 Q_PROPERTY 将 m_rosterItemModel 声明为 PROPERTY.我不能这样做,因为它说 QAbstractListModel 不是可复制.
- 我试图在 qml 文件中使用一个指向 m_rosterItemModel 的指针MainClass 中的 Q_INVOKABLE 函数.但这也无济于事.
有人可以帮我吗?
推荐答案
应该不需要任何元类型注册.您只需要调用 setContextProperty 并通过 pointer 传递模型:
There shouldn't be any metatype registration necessary.All you need to is to call setContextProperty and pass the model by pointer:
QQmlContext* context = view->rootContext(); //view is the QDeclarativeView
context->setContextProperty( "_rosterItemModel", &mainClassInstance->m_rosterItemModel );
在 QML 中使用它:
Use it in QML:
model: _rosterItemModel
通过指针很重要,因为 QObject 不是可复制构造的,并且复制它们无论如何都会破坏它们的语义(因为它们具有身份").
By pointer is important, as QObject's are not copy-constructible and copying them would break their semantics anyway (as they have an "identity").
直接注册模型的替代方法是注册主类的实例并使用 Q_INVOKABLE.在 MainClass 中:
The alternative to registering the model directly is to register your main class' instance and using Q_INVOKABLE. In MainClass:
Q_INVOKABLE RosterItemModel* rosterItemModel() const;
注册一个mainClass的实例(mainClassInstance再次假设为一个指针):
Registering an instance of mainClass (mainClassInstance again is assumed to be a pointer):
context->setContextProperty( "_mainInstance", mainClassInstance );
在 QML 中:
model: _mainInstance.rosterItemModel()
这篇关于如何将 C++ 模型公开给 QML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!