2

I want to invoke a qml method from c++ passing as a parameter a custom type.

This is my custom type (*Note that all the code I post is not exactly what i'm using, i've extracted the relevant parts, so if you try to compile it is possible that some changes have to be made)

Custom.h

class Custom : public QObject
{
    Q_OBJECT

    Q_PROPERTY(QString ssid READ getSSID WRITE setSSID)

public:

Q_INVOKABLE const QString& getSSID() {
        return m_ssid;
    }
     Q_INVOKABLE void setSSID(const QString& ssid) {
        m_ssid = ssid;
    }
}

private:
    QString m_ssid;
};
Q_DECLARE_METATYPE(NetworkInfo)

Custom.cpp

Custom::Custom(): QObject() {
    setSSID("ABC");
}


Custom::Custom(const Custom & other): QObject() {
    setSSID(other.getSSID());
}

This is where I call the qml method

void MyClass::myMethod(const Custom &custom) {
      QMetaObject::invokeMethod(&m_item,
                              "qmlMethod", Q_ARG(QVariant, QVariant::fromValue(custom)));
}

where QQuickItem& m_item

I have declared Custom as QML and QT meta types

qmlRegisterType<Custom>("com.mycustom", 1, 0, "Custom");

When i try to access the parameter inside the qml

import com.mycustom 1.0

function(custom) {
    console.log(custom.ssid)
}

I get

qml: undefined

If i do console.log(custom) I get

qml: QVariant(Custom)

so, i'd say my type is correctly imported into Qt (I have used it without problems instantiating it directly in Qml with

Custom {
 ....
}

Now, the question :)

Why can't I access the ssid property ?

1 Answer 1

3

Since you seem to have registered everything correctly, you might be encounting a bug that sometimes happen with QML where objects seem to be stuck in a QVariant wrapping. Try the following and see if it work.

import com.mycustom 1.0

property QtObject temp

function(custom) {
    temp = custom;
    console.log(temp.ssid);
}

Sometimes forcing your instance to be a QtObject will remove the annoying "QVariant wrapper" and solve the issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.