Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Exposing a user defined class / structure to qt meta object system and accessing the same in qml



  • Hi all,
    i was trying something like this..i had defined my own class in cpp which is as below.

    class myclass{
    public :
    int k;int m;
    QString str;
    };
    

    and my code has one more class which has a function ' retval' which will return an object of type myclass

    class reduntclass : public QObject {
    Q_OBJECT
    public :
    ....................
    ...................
    myclass retval() {
    ...............
    ..............
    return myclass_object;
    }//ret val ends here
    ....................
    ...................
    ....................
    ...................
    };//reduntclass class ends here
    

    and i have exposed "reduntclass" object to qml (with the help of context->setContextProperty("reduntclass", &(reduntclassobj));).also iam able to access reduntclass object from qml.problem is whenever i press a key , qml will call retval function as below

    onclicked {
    ...........
    var k = reduntclass.retval()
    ...........
    }
    

    but qml is not able identify the returned value ,and it gives the below errro message
    Error: Unknown method return type: myclass
    how i can solve this? i think qml is not able to identify myclass type,so i guess i need to expose my 'myclass' class to qt meta object system?


  • Moderators

    QML only understands QObjects. Your myclass should be a QObject, or at the very least a Q_GADGET.



  • if possible please give one example code



  • i tried the below code . in my .hpp file i have one structure and one class

    struct MyStruct {
        Q_GADGET
        int intval;
        QString str1;
        QString str2;
    };
    
    class MyClass:public QObject
        {
            Q_OBJECT
    public:
         MyClass(QObject *parent = nullptr){
              qDebug() <<"object created ";
        }
        MyStruct strObj;
        ~MyClass() {
        }
    MyStruct strObj;
       Q_INVOKABLE  MyStruct getMyStruct() const
         {
             return strObj;
         }
    };
    

    in main.cpp i have below piece of code

    MyClass classObj;
        context->setContextProperty("classObj",&classObj);
    

    on qml

    onClicked: {
                 var k  = classObj.getMyStruct()
    }
    

    but still getting below error message,what is wrong with the code?? please help!!!

    Error: Unknown method return type: MyStruct
    

  • Qt Champions 2019

    This post is deleted!

  • Moderators

    I'm not sure if Q_GADGET will work (QObject will for sure). Things to try:

    • return a pointer to your gadget, not a copy
    • declare pointer to your gadget as Qt meta type, register it with QML


  • You can't have a Q_GADGET and a Q_OBJECT in the same header file, moc is not smart enough to process that.


Log in to reply