Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Create chart in QT C++ and display it in QML



  • Hello,

    I'd like to create a chart in QT C++, and displaying it in QML.

    I created a class like this one:

    chart::chart(QObject *parent) : QObject(parent)
    {
    //![1]
    QLineSeries *series0 = new QLineSeries();
    QLineSeries *series1 = new QLineSeries();
    //![1]

    //![2]
    *series0 << QPointF(1, 5) << QPointF(3, 7) << QPointF(7, 6) << QPointF(9, 7) << QPointF(12, 6)
             << QPointF(16, 7) << QPointF(18, 5);
    *series1 << QPointF(1, 3) << QPointF(3, 4) << QPointF(7, 3) << QPointF(8, 2) << QPointF(12, 3)
             << QPointF(16, 4) << QPointF(18, 3);
    //![2]
    
    //![3]
    QAreaSeries *series = new QAreaSeries(series0, series1);
    series->setName("Batman");
    QPen pen(0x059605);
    pen.setWidth(3);
    series->setPen(pen);
    
    QLinearGradient gradient(QPointF(0, 0), QPointF(0, 1));
    gradient.setColorAt(0.0, 0x3cc63c);
    gradient.setColorAt(1.0, 0x26f626);
    gradient.setCoordinateMode(QGradient::ObjectBoundingMode);
    series->setBrush(gradient);
    //![3]
    
    //![4]
    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle("Simple areachart example");
    chart->createDefaultAxes();
    chart->axisX()->setRange(0, 20);
    chart->axisY()->setRange(0, 10);
    chart->setMinimumHeight(480);
    chart->setMinimumWidth(640);
    

    }

    Then in main file I registered the C++ chart class:

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    
    qmlRegisterType<chart>("myClass.com",1,0,"Chart");
    
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
    return app.exec();
    

    }

    In QML file I wrote:

    import QtQuick 2.5
    import QtQuick.Controls 1.4
    import QtQuick.Dialogs 1.2
    import myClass.com 1.0

    ApplicationWindow {
    visible: true
    width: 640
    height: 480

    Chart {
        id: chart
    
    }
    

    }

    When I launch the program appear a white window.

    Does someone help me to solve this problem?

    Many thanks.

    Best Regrads,

    Chobin


Log in to reply