Search code examples
c++qtqchart

QChart initialization causes an EXCEPTION VIOLATION


When I initialize a QChart, it causes an Unhandled exception EXCEPTION_ACCESS_VIOLATION. I have seen this same exception violation error on Qt Forums when others try to initialize a QChart, however their suggestions do not resolve the issue for me. Their suggestions are to make sure that within Visual Studio's project Properties, that in C++/C > General the necessary Qt folders are included (which is \include\QtCharts) and that in Linker > Input the necessary .lib files are included (which is \lib\Qt5Charts.lib). I am using other modules as well, and those are included properly. I am building Release.

The following is a cleaned-up version of my code, containing only what is absolutely necessary. The actual .cpp file is much larger.

#include <QPainter>
#include <QPen>
#include <QApplication>
#include <QMainWindow>
#include <QtCharts> // for QScatterPlot
#include <QChartView>
#include <iostream>

int Graphics::OpenGraphic()
{
    char* myargv[1];
    int myargc = 1;
    myargv[0] = strdup("");

    QScatterSeries* redSeries = new QScatterSeries;
    redSeries->append(0, 6);
    redSeries->append(2, 4);
    redSeries->setColor(Qt::red);

    QScatterSeries* blueSeries = new QScatterSeries;
    blueSeries->append(3, 8);
    blueSeries->append(7, 4);
    blueSeries->append(10, 5);
    blueSeries->setColor(Qt::blue);

    QChart* chart = new QChart(); // This causes an Unhandled exception EXCEPTION_ACCESS_VIOLATION at 0x00007FFA1FE24CBC

    chart->addSeries(redSeries);
    chart->addSeries(blueSeries);

    QApplication a(myargc, myargv);
    QMainWindow w;

    //w.setCentralWidget(chartView);
    w.resize(400, 300);

    w.show();

    return a.exec();
}

Any insight is appreciated. This seems to be a tricky issue.

edit: Also there are no red squiggles underlining QChart or anything within VS.


Solution

  • Your problem is you created the QChart before you created your QApplication instance. The documentation for QApplication states: Since the QApplication object does so much initialization, it must be created before any other objects related to the user interface are created.

    https://doc.qt.io/qt-5/qapplication.html#details

    To fix move the QApplication a(myargc, myargv); line above QChart *chart = new QChart();