Important: Please read the Qt Code of Conduct -

How to Expose a Qt C++ Class to QML

  • In QT I use this method to define a class in another class


    #ifndef RealTime_H
    #define RealTime_H
    #include <QDialog>
    #include "randomwalk.h"
    class RealTime : public QDialog {
        RealTime(QWidget *parent = 0);
         // RandomWalk is a thread class
         RandomWalk *dataSource;
    static void OnData(void *self, double elapsedTime);


    RealTime::RealTime(QWidget *parent) :
     // Start the random data generator
        dataSource = new RandomWalk(OnData, this);

    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[])
        QGuiApplication app(argc, argv);
        qmlRegisterType <RealTime>("realt",1,0,"RealTime");
        qmlRegisterType<RandomWalk> ("thread",1,0,"RandomWalk");
        QQmlApplicationEngine engine;
        if (engine.rootObjects().isEmpty())
            return -1;
        return app.exec();


    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
      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 ?

  • I know it creates when we define an object,
    But how do I define an onData input?

  • Qt Champions 2018

    What's an onData input? What do you want to do with it?

    Have you read this page ?
    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_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:

        id: mThread
        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 :)

Log in to reply