Using Qt c++ function in qml
-
wrote on 20 Mar 2012, 13:05 last edited by
I tried using a cpp function in my qml but am not able to do it properly.
Here is the codemain.qml
@// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1Rectangle {
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(QLatin1String("qml/try2/main.qml")); QDeclarativeEngine *engine = viewer.engine(); QDeclarativeContext *context = engine->rootContext(); context->setContextProperty("main", engine); viewer.showExpanded(); return app->exec();
}
@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. -
wrote on 20 Mar 2012, 13:20 last edited by
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
1/2