qtqmlqtquick2qquickwidget

Drawing Simple Bar Charts in QML


Using Qt/C++ for a normal widget application, and the QQuickWidget with QML, how would I draw a simple bar chart like the following?

enter image description here

I guess this question goes back to how the QML would be composed.


Solution

  • These instructions are for Mac OSX. You will have to vary this slightly for Windows or Linux:

    1. In a Qt/C++ widget-based application, add the QQuickWidget to your MainWindow and set it to around 500x500 size. Don't set the Source property on that widget.

    2. In your .pro project file, adjust your QT parameter to include quickwidgets. Also, add the following to the bottom of this file:

    mac {
      Resources.files = objects
      Resources.path = Contents/MacOS
      QMAKE_BUNDLE_DATA += Resources
    }
    
    1. Create an objects folder inside your project folder as a general purpose container that will get copied out to the production .app file when the application is run.

    2. Inside that objects folder in your project folder, create a qml folder.

    3. Download the files from this location into that qml folder, and be sure to unzip that zip download.

           https://github.com/jwintz/qchart.js

    1. Create a bar.qml file in that same qml directory. The contents of that file should look like so:
    import QtQuick 2.0
    
    import "."
    import "QChart.js"        as Charts
    import "QChartGallery.js" as ChartsData
    
    Chart {
      id: chart_bar;
      width: 450;
      height: 450;
      chartAnimated: false;
      chartData: ChartsData.ChartBarData;
      chartType: Charts.ChartType.BAR;
    }
    
    1. In your mainwindow.cpp, add this in your main() function sometime after you do the ui->setupUi(this); line:
    QString sQMLPath = QCoreApplication::applicationDirPath().append("/objects/qml/bar.qml");
    ui->quickWidget->setSource(QString("file://").append(sQMLPath));
    

           This will ensure that your QML file has the proper path when it is deployed in production (or        debug).

    Note: I tried loading these QML and JS files via a Qt Resource (qrc:// pathing), but it didn't seem to properly like that and complained either about not finding the QChart.qml file or a message that "QChart is not a type".

    1. When you run your application, you should see a bar chart. You can then study the chart.js website for more info on how to manipulate this chart.