Using Qt c++ function in qml



  • I tried using a cpp function in my qml but am not able to do it properly.
    Here is the code

    main.qml
    @// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
    import QtQuick 1.1

    Rectangle {
    width: 360
    height: 360
    visible: true
    Text {
    text: qsTr("Hello World")
    anchors.centerIn: parent
    }
    MouseArea {
    anchors.fill: parent
    onClicked: {
    console.log("hello in qml")
    Product.abc(5);
    }
    }
    }
    @

    main.cpp
    @#include <QtGui/QApplication>
    #include "qmlapplicationviewer.h"
    #include "product.h"
    #include <QDeclarativeEngine>
    #include <qmlapplicationviewer.h>
    #include <QDeclarativeContext>
    #include<QDebug>

    Q_DECL_EXPORT int main(int argc, char *argv[])
    {
    QScopedPointer<QApplication> app(createApplication(argc, argv));

    Product p;
    p.abc(1);
    
        QmlApplicationViewer viewer;
        viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
        viewer.setMainQmlFile&#40;QLatin1String("qml/try2/main.qml"&#41;);
    
    
        QDeclarativeEngine *engine = viewer.engine();
        QDeclarativeContext *context = engine->rootContext();
    
        context->setContextProperty("main", engine);
        viewer.showExpanded();
    return app->exec&#40;&#41;;
    

    }
    @

    product.cpp
    @#include "product.h"
    #include<QDebug>

    Product::Product()
    {
    qDebug()<<"hello in constructor";
    }
    void Product::abc(int a)
    {
    qDebug()<<"a= "<<a;
    }
    @

    I know there should be error in using unknown type Product in qml but what i dont know is how to make it available there.
    Can anyone help me out.



  • You have to subclass QDeclarativeItem, or at least QObject, add use the Q_PROPERTY macro for all properties you need to access from QML and so on, read in detail here:
    http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html


Log in to reply
 

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