QML使用QtCharts 报错

新建一个 Qt Quick Application 应用,测试QtCharts模块报错:

import QtQuick 2.6
import QtQuick.Window 2.2
import QtCharts 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ChartView {
        width: 400
        height: 300
        theme: ChartView.ChartThemeBrownSand
        antialiasing: true

        PieSeries {
            id: pieSeries
            PieSlice { label: "eaten"; value: 94.9 }
            PieSlice { label: "not yet eaten"; value: 5.1 }
        }
    }
}

运行报错:
ASSERT: “!”No style available without QApplication!”” in file kernel\qapplication.cpp, line 1060
ASSERT: “!”No style available without QApplication!”” in file kernel\qapplication.cpp, line 1060

查看官方文档有这样一句话:

Note: Since Qt Creator 3.0 the project created with Qt Quick Application wizard based on Qt Quick 2 template uses QGuiApplication by default. As Qt Charts utilizes Qt Graphics View Framework for drawing, QApplication must be used. The project created with the wizard is usable with Qt Charts after the QGuiApplication is replaced with QApplication.

意思大概就是要在qtquick中使用QtCharts模块的话必须使用QApplication代替QGuiApplication。

pro文件中添加:

QT += widgets

修改main.cpp为:

#include 
#include 

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

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

运行正常。

你可能感兴趣的:(qml,qt,Qt的研究与学习)