Bruno Gallego
Bruno Gallego

Reputation: 29

QT QML + C++ MVVM

As far as I know in QT QML is not possible to instantiate a C++ class in QML Component, unless it is a QQuickItem. I would not like to put all ViewModels on ViewEngine context because it is a very bad pratice create all classes in memory without using.

My question is: How can I instantiate a C++ ViewModel ou Services/API from a single QML component without usnig ViewEngine Context. Do ViewModels have to be QQuickItem type?

Upvotes: 0

Views: 674

Answers (1)

JarMan
JarMan

Reputation: 8277

C++ objects do not need to be QQuickItems, they need to be QObjects. You just need to register your class with the QQmlEngine, like this:

qmlRegisterType<MyObject>("my.component.library", 1, 0, "MyObject");

Then in your qml files, you can instantiate that class like this:

import my.component.library 1.0

MyObject {
    ...
}

Upvotes: 3

Related Questions