Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use QVariant or MyCustomType* to pass an object from Qml to C++?

I have C++ class User

class User : public QObject
{
    Q_PROPERTY(QString login READ login WRITE setLogin NOTIFY loginChanged)
    Q_PROPERTY(QString password READ password WRITE setPassword NOTIFY passwordChanged)
    ...
}

Also I have Qml SignIn form with button which calls this code when clicked:

var user = userComponent.createObject()
user.login = loginTextField.text
user.password = passwordTextField.text
signInInteractor.signIn(user)

SignInInteractor is a C++ class

class SignInInteractor : public QObject
{
    Q_INVOKABLE void signIn(User* user);
    Q_INVOKABLE void signIn(QVariant user);
    ...
}

And my question is should I use User* or QVariant as argument type? What advantages and disadvantages they have?

like image 209
Divano Avatar asked Dec 19 '25 11:12

Divano


1 Answers

Your custom type is QObject derived, so you can easily work on it on a QObject * level from QML. You will be able to access properties, slots or invokables, and functions directly, without having to do anything extra.

You will however have to add the Q_OBJECT macro, which is currently missing from your code, so the types get the MOC treatment that will generate the necessary meta data for them, which is what QtQuick will be using for introspection.

If you pass it as a variant, it will be like an opaque pointer, you won't able to do much with it from QML other than to pass it around. It only makes sense when the type is unsupported by QML, and QObject is more like a first class citizen there.

like image 107
dtech Avatar answered Dec 21 '25 04:12

dtech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!