Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to dynamically create qml windows

Tags:

qt

qt-quick

qml

I'm working on a Qt application and I need to create windows dynamically. Each window consists of QObject-based c++ backend and qml-based interface. Each window needs to be connected to the bunch of signals emitted by core classes. Current solution is to derive window from QQuickView, connect signals to it and load qml using setSource(). Is it a right way or there is a better way? Is it better to use one QQmlEngine for all windows (and use this engine as parent for every window) or create new engine for each new window?

like image 384
Bearded Beaver Avatar asked Nov 07 '22 23:11

Bearded Beaver


1 Answers

For this I would expose a c++ model to the QML code. Since this model would be dynamic (elements can be added or removed), I'd use a QAbstractItemModel derived model that can inform the views that some elements are added/removed. Using something else like a QList<QObject*> would mean that you'd have to tell the view that the entire model should be reloaded after each change.

Instead of implementing the model from scratch, you could use a class like QQmlObjectListModel from Qt QML Tricks, it exposes a QList-like API from c++ but is a QAbstractItemModel exposing the QObject properties as roles under the scene.

Another solution that you could use if you don't want to use QObjects is benlau's QSyncable (I've actually used this in a similar situation to yours, where I expose my screens in a model and instantiate a Window displaying a taskbar for each).

Then, I'd use a QQmlApplicationEngine and expose the model to it with setContextProperty. A QQuickView is already a window, so I don't think you want to use that, better to manage your windows manually in the QML code.

Then in your QML code, use an Instantiator as your root object, set your model, and use Window as its delegate :

Instantiator {
    model: yourModel
    Window {
        /* ... */
    }
}
like image 119
GrecKo Avatar answered Dec 23 '22 08:12

GrecKo