[Solved] error while Embedding C++ object into qml components



  • I wanted to check out how well the embedding of c++ objects in qml works
    For this purpose I have the following code in QT Quick Application

    main.cpp
    @#include <QtGui/QApplication>
    #include <QDeclarativeContext>
    #include <QKeyEvent>
    #include "qmlapplicationviewer.h"

    class Factorial : public QObject {
    int x;

    public:
    Factorial(int z) {
    x=z;
    }
    Q_INVOKABLE QString fact() const {
    int f=1;
    QString str;
    for(int i=x;i>0;i--)
    f=f*i--;
    str=QString::number(f);
    return str;
    }
    };

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    QmlApplicationViewer viewer;
    Factorial f(10);
    viewer.rootContext()->setContextProperty("factorial",&f);
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile&#40;QLatin1String("qml/test1/main.qml"&#41;&#41;;
    viewer.showExpanded(&#41;;
    
    return app.exec(&#41;;
    

    }
    @

    main.qml:
    @import QtQuick 1.0

    Rectangle {
    id: rectangle1
    width: 360
    height: 360

    Rectangle {
        id: rectangle2
        x: 93
        y: 89
        width: 157
        height: 80
        color: "#912323"
        MouseArea   {
            id:marea1
            anchors.fill: parent
            onClicked: console.log(factorial.fact(&#41;&#41;
        }
    }
    

    }
    @

    Now when I run the code and click the mouse area I get the following error message
    file:///home/sinjar/nokia/test1-build-simulator/qml/test1/main.qml:18: TypeError: Result of expression 'factorial.fact' [undefined] is not a function.

    Can someone please tell me where i am going wrong
    Thanks


  • Moderators

    • Add the Q_OBJECT macro to your Factorial class.
    • Either break the Factorial class into its own cpp and header files (easiest), or include the generated moc file manually.


  • @mlong: Thanks....


  • Moderators

    No problem! If it's working for you, be sure and change the thread title to add [Solved]. Thanks!


Log in to reply
 

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