主要有两种方法:
方法一:
1、通过cpp的操作获取应用程序的可执行文件目录,设置engine's root context属性,以便在qml里通过appDir获取文件目录
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
//该句要加在engine.load(QUrl(QStringLiteral("qrc:/main.qml")))之前,
//设置engine's root context属性,以便在qml里通过appDir获取文件目录
engine.rootContext()->setContextProperty("appDir", qApp->applicationDirPath());
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
2、在qml文件里即可获取appDir的值
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log(appDir)
}
}
方法二、
在qml里调用Qt.application.arguments[0]获取全路径;