前言

出现这个问题所在呢,是因为我原QQuickView 搭配Item 中出现使用的ChartView去绘图地方重新构建使用在QQmlApplicationEngine搭配window方式,这种方式下是不能加载ChartView,即使你在pro工程文件中添加了QT += charts qml quick 。因为默认启动的application不一样导致。

原因分析

常见加载qml文件的两种方式

  1. QQuickView 加载 Item
QApplication app(argc, argv);
QQuickView view;

view.setResizeMode(QQuickView::SizeRootObjectToView);

view.setSource(QUrl("qrc:/mainqml"));

 view.show();

Item
{
    width: 640
    height: 480
    title: qsTr("Scroll")
}
  1. QQmlApplicationEngine搭配window
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

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

    return app.exec();
ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Scroll")

    ScrollView {
        anchors.fill: parent

        ListView {
            width: parent.width
            model: 20
            delegate: ItemDelegate {
                text: "Item " + (index + 1)
                width: parent.width
            }
        }
    }
}

由于当时我没太注意QApplication加载方式,然后就把带ChartView下的直接qml加载到带有 QGuiApplication app(argc, argv);去load结果导致这个问题出现了,解决方案只需要将 QGuiApplication app(argc, argv); 修改为QApplication app(argc, argv);即可。 因为QApplication 继承自QGuiApplication ,对于有继承基本Qt widgets的 需要用QApplication , 而ChartView来自于Qt widgets。

以下是QApplication 说明
QApplication specializes QGuiApplication with some functionality needed for QWidget-based applications. It handles widget specific initialization, finalization.
For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time. For non-QWidget based Qt applications, use QGuiApplication instead, as it does not depend on the QtWidgets library.
Some GUI applications provide a special batch mode ie. provide command line arguments for executing tasks without manual intervention. In such non-GUI mode, it is often sufficient to instantiate a plain QCoreApplication to avoid unnecessarily initializing resources needed for a graphical user interface. The following example shows how to dynamically create an appropriate type of application instance:

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐