Qt invoking qml function with custom QObject type

和自甴很熟 提交于 2019-12-23 02:52:24

问题


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:


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.



来源:https://stackoverflow.com/questions/23271195/qt-invoking-qml-function-with-custom-qobject-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!