Qt Forum

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

    Update: Forum Guidelines & Code of Conduct

    Using Qt c++ function in qml

    General and Desktop
    1
    2
    2132
    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
      akhil last edited by

      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.

      1 Reply Last reply Reply Quote 0
      • ?
        Guest 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 Reply Last reply Reply Quote 0
        • First post
          Last post