SetContextProperty of a class that extends Object



  • Hi,

    I saw in this website how to make a class that extends Object to set an instance as a property.

    http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html#embedding-c-objects-into-qml-components

    I did it as they say but I had some troubles and finally I had to separate to another file the class, but when I try to do this

    @ApplicationData data;
    view.rootContext()->setContextProperty("applicationData", &data);@

    it gives this error:

    'QVariant::QVariant(void*)' is private

    I have tried to search the problem, and read about the classes priviledges but I don't know how to give an object as a property then. Thank you in advance.



  • I think you have to write much more of code...
    Maybe you forgot Q_OBJECT macro...



  • Thank you for the fast answer.

    I did just what the example was saying

    @class ApplicationData : public QObject
    {
    Q_OBJECT
    public:
    Q_INVOKABLE QDateTime getCurrentDateTime() const {
    return QDateTime::currentDateTime();
    }
    };
    @

    Well I had to write it in a separated file with the headers but it doesn't complaint about that, just gives back the error QVariant::QVariant(void*)'



  • I discovered the problem but not the solution. If I delete the macro Q_OBJECT from the code it doesn't give any problem, but I can not call the functions inside from the QML. But when I include it in the code it gives the problem:

    @ undefined reference to `vtable for ...' @



  • you need keep the Q_OBJECT macro (used on moc process), this is necessary to make your class a QObject.

    try call the function with explicitly cast:
    view.rootContext()->setContextProperty("applicationData", (QObject*)&data);



  • Yes I included it, I wrote in the header Q_OBJECT as the example but it's all the time appearing this error.

    @undefined reference to `vtable for ...'@

    With the explicitly cast it doesn't give me the other error. It's a beginning, thanks!



  • Are you using qmake?
    if yes, try put the Q_OBJECT macro, then re-run the qmake program, after that compile your program.

    A moc file need be genereted and included on your src list. (qmake do this for you)



  • I was doing it wrong, because what you said, I was doing it copying it directly. I discovered the way to add it correctly with Qtcreator.

    Really helpfull, Thanks a lot!



  • Use QVariant::fromValue:
    @view.rootContext()->setContextProperty("applicationData", QVariant::fromValue(data));@

    http://qt-project.org/doc/qt-4.8/declarative-modelviews-stringlistmodel-main-cpp.html


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.