Unsolved How to Expose a Qt C++ Class to QML
-
In QT I use this method to define a class in another class
.h:
#ifndef RealTime_H #define RealTime_H #include <QDialog> #include "randomwalk.h" class RealTime : public QDialog { Q_OBJECT public: RealTime(QWidget *parent = 0); ~RealTime(); // RandomWalk is a thread class RandomWalk *dataSource; static void OnData(void *self, double elapsedTime); #endif
.cpp:
RealTime::RealTime(QWidget *parent) : QDialog(parent) { // Start the random data generator dataSource = new RandomWalk(OnData, this); dataSource->start(); }
Now in QML I register c++ class and set id in .qml file
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QtQml> #include <realtime.h> #include <randomwalk.h> int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); qmlRegisterType <RealTime>("realt",1,0,"RealTime"); qmlRegisterType<RandomWalk> ("thread",1,0,"RandomWalk"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
.qml:
import QtQuick 2.11 import QtQuick.Controls 2.4 import realt 1.0 import thread 1.0 Page { id: page width: screen.width height: screen.height property alias button1: button1 RealTime{ id:mRealtime } RandomWalk{ id:mThread } Button { id: button x: -74 y: -110 text: qsTr("Config 2") anchors.verticalCenterOffset: -6 anchors.horizontalCenterOffset: -24 anchors.horizontalCenter: parent.horizontalCenter anchors.verticalCenter: parent.verticalCenter // onClicked: }
How should I define
dataSource = new RandomWalk(OnData, this);in qml ? -
This may help you.
https://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html -
I know it creates when we define an object,
RandomWalk{
id:mThread
}
But how do I define an onData input? -
What's an onData input? What do you want to do with it?
Have you read this page https://doc.qt.io/qt-5/qtqml-cppintegration-overview.html ?
I'm not sure what you need but it might be a property, a signal or a slot. -
In your RealTime class you need to expose the RandomWalk property to qml, using setters and getters and the macro Q_PROPERTY.
Something like this:class RealTime : public QDialog { Q_OBJECT Q_PROPERTY(RandomWalk walk READ randomWalk WRITE setRandomWalk /*NOTIFY randomWalkChanged*/) // in line above walk is the property name that gets exposed to qml RandomWalk randomWalk() { return *randomWalk;} public slots: void setRandomWalk(RandomWalk randomWalk_){ dataSource = new RandomWalk(randomWalk_);} ....... RandomWalk *dataSource; .........
Then in qml you can do:
RandomWalk{ id: mThread } RealTime{ id: mRealtime walk: mThread }
Note that I havent tested the code above, so you may need to do some tunning, but hopefully you get the ideia :)