Can I expose a C++ model as Q_Property?
-
Yes, here is some help: https://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html.
-
my problem here is the following:
I write my custom plotting component (a QQuickItem). I might have several instances of these plots in my application, and each object has its own model, e.g. for the x-ticks.
I guess using
ctxt->setContextProperty("myModel",_tickModel);
will not work as I will have several instances, and the name would then not be unique. Doing
qmlRegisterType<TickModel>(uri, 1, 0, "TickModel");
would allow me to create the model in qml, but it should be created in C++. Would using qmlRegisterType allow me to do something like this?:
class Plot : public QQuickItem { Q_OBJECT public: Q_INVOKABLE TickModel getTickModel()
-
@maxwell31 said in Can I expose a C++ model as Q_Property?:
Would using qmlRegisterType allow me to do something like this?:
class Plot : public QQuickItem {
Q_OBJECT
public:
Q_INVOKABLE TickModel getTickModel()qmlRegisterType()
will allow you to create a new instance of the given class. If you don't need to create an instance I would suggest you to do it like this:class Plot : public QQuickItem { Q_OBJECT public: Q_INVOKABLE QObject* getTickModel();
But be aware that if the TickModel object did not have a parent, QML engine will take ownership and delete it when QML did not need it anymore.
-
@maxwell31 Hi,
isdataList
really an instance of QAbstractItemModel ?
If yes, why are you wrapping your model withQVariant::fromValue()
?Better to do:
ctxt->setContextProperty("myModel", dataList);
Or share an object which share the model as property:
class MyClass: public QObject { Q_OBJECT Q_PROPERTY(MyModel* model READ model) ... }
By this way you will have access to the interface of QAbstractItemModel (MyModel) from QML side (auto-completion)
-
@Gojir4 said in Can I expose a C++ model as Q_Property?:
is dataList really an instance of QAbstractItemModel ?
If yes, why are you wrapping your model with QVariant::fromValue() ?Sorry, I just copied from the documentation. I corrected my post
-
Hi @maxwell31
You can also try with qRegisterMetaType.
Q_PROPERTY(MyModel* model MEMBER m_Model NOTIFY modelChanged)
then
qRegisterMetaType<MyModel *>();
All the best.