Register the C ++ abstract class in the QML plugin and access it from QML


I am writing a Qt application.
I have separated my application to the QML interface and the C ++ plugin server.
In my C ++ plugin, I have an abstract session class that I would like to open in QML, and I also have several implementations of this class.
I would like my QML interface to know only about the Session class and not worry about the specifics of a kind of session.
I tried several qmlRegister * options to register my session type with QML, but any session must be specific (as in the case of qmlRegisterType), or it registers a penalty, but I just can’t refer to the session type from QML, as in the property Session session without even creating a session instance from QML.
Does anyone know how I should approach this?

UPDATE :
An example of what did not work:
In main.cpp:

 char const* const uri = "com.nogzatalz.Downow"; qmlRegisterUncreatableType<downow::Session>(uri, 1, 0, "Session", "Abstract type"); 

In DowNow.qml:

 import QtQuick 2.0 import com.nogzatalz.Downow 1.0 Item { property Session session } 
+6
source share
2 answers

As far as I know, it is impossible to create a variable using an abstract class as a definition.

You can declare a session variable as QtObject in qml code, you just lose the qtcreator autocompletion function.
However, the entire property is declared using the Q_PROPERTY macro, and all Q_INVOKABLE functions will still be available at run time.

If you want to have almost the same semantics, I suggest you create a single-line C ++ class that you register in QML using qmlRegisterSingletonType and include this class in the "session" variable. Then save the qmlRegisterUncreatableType in your abstract session class, so you can write something like this in the qml code:

 MySingleton.session 

And save autocomplete for qml in qtcreator.
As a bonus, you can also create a “SessionChanged” signal if your users can log in / out several times without restarting the application.

0
source

I worked with qmlRegisterInterface. My virtual call is InputDeviceConfigurator:

 class InputDeviceConfigurator : public QObject { Q_OBJECT public: explicit InputDeviceConfigurator(QObject *parent = 0); Q_INVOKABLE virtual QString deviceId() = 0; } 

I will register it as follows:

 qmlRegisterInterface<InputDeviceConfigurator>( "InputDeviceConfigurator" ); 

And then use the inherited JoystickConfigurator class:

 class JoystickConfigurator : public InputDeviceConfigurator { public: JoystickConfigurator( JoystickDevice * device ); // InputDeviceConfigurator interface virtual QString deviceId() override; } 

And how can I use it:

  Component.onCompleted: console.log( UserInputManagement.getConfigurator().deviceId() ) 

UserInputManagement is just a Singleton with:

 Q_INVOKABLE InputDeviceConfigurator * getConfigurator(); 
-1
source

Source: https://habr.com/ru/post/972140/


All Articles