从c++显示qml与qmlscene显示的内容不同

Displaying qml from c++ differs from what qmlscene shows

本文关键字:显示 qmlscene c++ qml      更新时间:2023-10-16

我正在尝试运行一个基本程序,该程序通过c++显示一个简单的qml文件。加载QQmlEngine等的代码如下:

#include <QQmlEngine>
#include <QQmlComponent>
#include <QDebug>
#include <QGuiApplication>
#include <QQuickView>
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlEngine engine;
    QQmlComponent component(&engine);
    QQuickWindow::setDefaultAlphaBuffer(true);
    component.loadUrl(QUrl("qrc:///qmlFiles/main.qml"));
    if ( component.isReady() )
        component.create();
    else
        qWarning() << component.errorString();
    QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(),SLOT(quit()));
    return app.exec();
}

qml(简化)文件为:

import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Dialogs 1.0

ApplicationWindow
{
    width:800
    height:600
    //background: "white"
    visible:true
    function selectFile()
    {
        fileChooser.visible=true;
    }
    menuBar:MenuBar {
            Menu{
                    title:"File"
                    MenuItem{
                        text:"Choose File"
                        shortcut: "Ctrl+F"
                        onTriggered:{
                            selectFile();
                        }
                    }

                    MenuItem {
                        text:"Quit"
                        shortcut: "Ctrl+Q"
                        onTriggered: Qt.quit()
                    }
            }
    }
   FileDialog{
        id:fileChooser
        visible:false
        modality:Qt.WindowModal
        title:"Choose data file"
        onAccepted:{
            console.log(fileChooser.fileUrls)
            visible:false
        }
        onRejected:{
            console.log("Cancel")
            visible:false
        }
    }
}

当我使用qmlscene从终端运行文件时,显示的内容与从c++程序运行文件时不同。

我的猜测是,C++实现无法使用特定于平台的东西(例如QFileDialog),而只能使用这些东西的qml实现。

我想我需要以不同的方式加载qml文件,但如何加载呢?

发现QGuiApplication存在一些重写或其他内容。

将其更改为QApplication,看起来和qmlscene中一样好。