Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Call for Presentations - Qt World Summit

    Qml variant to custom QtObject

    QML and Qt Quick
    3
    5
    1708
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • A
      antonio last edited by

      I have 2 different C++ objects using Q_PROPERTY and Q_INVOKABLE for a function, in my qml file I have this:

      @
      include MyObject 1.0 //from c++
      incluce MyInvokable 1.0 //from c++

      property variant myVariant

      MyObject{
      id:myObject
      }

      MyInvokable{
      id: myInvokable
      }
      onCallFunction:{
      myVariant = myObject;
      myInvocable.invokableFunction( myVariant )
      }@

      At MyInvokable function I can't get the value of MyObject:

      @
      void MyInvocable::invocableFunction(QVariant variant)
      {
      MyObject myObject = qvariant_cast<MyObject>(variant) ; //cant convert to MyObject
      qDebug() << "foo: " << myObject.foo();
      }
      @

      MyObject has the macro
      @Q_DECLARE_METATYPE(MyObject);@

      How can I convert QVariant to my custom Object ?

      Regards

      1 Reply Last reply Reply Quote 0
      • B
        beemaster last edited by

        You don't need to convert from QVariant, try to work with QObject* pointers.
        @
        void MyInvocable::invocableFunction(QObject* object)
        {
        MyObject* myObject = static_cast<MyObject*>(object);
        qDebug() << "foo: " << myObject->foo(); // pointers!
        }
        @

        1 Reply Last reply Reply Quote 0
        • T
          tzander last edited by

          I agree with beemaster, just that I would replace that static_cast with a much more safe qobject_cast.

          1 Reply Last reply Reply Quote 0
          • T
            tzander last edited by

            Reading your qml, you use a variant there too. Its almost never useful to have a variant in QML, since QML is typesafe. In this case you don't need that property in the first place, but otherwise you should consider using the QtObject type instead;

            1 Reply Last reply Reply Quote 0
            • A
              antonio last edited by

              Thanks beemaster, Thomas Zander I have taken your advices and now my program works.

              1 Reply Last reply Reply Quote 0
              • First post
                Last post