Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register a C++ abstract class in a QML plugin and refer to it from QML


I'm writing a Qt app.
I've separated my app to a QML frontend and a C++ plugin backend.
In my C++ plugin I have a Session abstract class that I would like to expose to QML and I also have a few implementations of that class.
I would like my QML frontend to only know of the Session class and not be bothered with the specifics of which kind of session it is.
I tried a few variations of qmlRegister* to register my Session type with QML but either Session needs to be concrete (as in qmlRegisterType's case) or it registers fine but I simply cannot refer to the Session type from QML as in property Session session without even instantiating a Session from QML.
Does anyone know how I should approach this?

UPDATE:
An example of what didn't 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
}
like image 530
Tal Zion Avatar asked Jul 13 '14 12:07

Tal Zion


1 Answers

I got this working 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 register it as follows:

qmlRegisterInterface<InputDeviceConfigurator>( "InputDeviceConfigurator" );

And then use an inherited class JoystickConfigurator:

class JoystickConfigurator : public InputDeviceConfigurator
{
public:
    JoystickConfigurator( JoystickDevice * device );

    // InputDeviceConfigurator interface
    virtual QString deviceId() override;
}

And than I can use it:

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

UserInputManagement is just a Singleton with:

Q_INVOKABLE InputDeviceConfigurator  * getConfigurator();
like image 104
user3054986 Avatar answered Nov 01 '22 00:11

user3054986