Quantcast
Channel: Jobs
Viewing all articles
Browse latest Browse all 18427

QML and C++ Integration

$
0
0
Hello, I have gotten communication from c++ and QML using the Q_PROPERTY macro with basic types such as QString and int, but I cannot get it to work with my own custom class that extends QObject. Here is my Code: //simple.h #include <QObject> #include <QMetaType>   class Simple : public QObject {      Q_Object      Q_PROPERTY(int hour READ getHour WRITE setHour NOTIFY hourChanged)   public:      explicit Simple(QObject *parent = 0);      int getHour();      void setHour(int hour);   signals:      void hourChanged(int);   private:      int _hour; };   Q_DECLARE_METATYPE(Simple*) //simple.cpp #include "simple.h"   Simple::Simple(QObject *parent)      : QObject(parent) {      _hour = 129;     }   int Simple::getHour() {      return _hour; }   void Simple::setHour(int hour) {      _hour = hour;      emit hourChanged(_hour); } //step.h #include <QObject> #include <QMetaType> #include "simple.h"   class Step : public QObject {      Q_OBJECT      Q_PROPERTY(Simple* sim READ getSim)   public:      explicit Step(QObject *parent = 0);      Simple* getSim();   private:      Simple* _sim; }; //step.cpp #include "step.h"   Step::Step(QObject *parent)      : QObject(parent) {      qRegisterMetaType<Simple*>("Simple");      _sim = new Simple(); }   Simple* Step::getSim() {      return _sim; } //main.cpp #include <QtGui/QGuiApplication> #include "qtquick2applicationviewer.h" #include <QQmlContext> #include "step.h"   int main(int argc, char *argv[]) {      QGuiApplication app(argc, argv);      QtQuick2ApplicationViewer viewer;        Step step;      viewer.rootContext()->setContextProperty("step", &step);        viewer.setMainQmlFile(QStringLiteral("qml/Cineflux_001/main.qml"));      viewer.showExpanded();      return app.exec(); } //main.qml import QtQuick 2.0   Rectangle {      width: 200; height: 200;        Component.onCompleted: {           console.log(step.sim); //prints QVariant(Simple*)           console.log(step.sim.hour) //prints undefined      } } I do not understand why step.min prints the object, but when I try and access the hour property it gives me undefined. Is this because the c++ object is a pointer? I am not sure. I have fiddled with this a lot and I either get META compile errors or undefined. Please help me. Thank you

Viewing all articles
Browse latest Browse all 18427

Trending Articles