目录
engine.rootContext()->setContextProperty("appDir",app.applicationDirPath());
1.调用的qml封装文件不在当前目录或者子目录时候,直接引入路径:
四、qml中Quick 1.0库和Quick 2.0库如何同时引用?
前言
qml开发过程经常遇到路径问题花样还不少,在此总结下。
提示:以下是本篇文章正文内容,下面案例可供参考
一、qml中如何获取App运行路径?
1.Cpp传入路径:
engine.rootContext()->setContextProperty("appDir",app.applicationDirPath());
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("appDir",app.applicationDirPath());
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
qml中调用:
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log("ssss "+appDir)
}
}
2.qml中直接获取命令行参数地址:
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log("ssss "+Qt.application.arguments[0])
}
}
二、qml中source路径如何正确引入?
1.绝对路径:
"file:///"开头
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log("ssss "+Qt.application.arguments[0])
}
Image {
id: name
source: "file:///"+appDir+"/test.svg"
}
}
3.资源路径:
建议加入资源文件后自己右键复制资源文件路径粘贴即可
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log("ssss "+Qt.application.arguments[0])
}
Image {
id: name
source: "qrc:/image/test.png"
}
}
三、qml中import路径如何正确使用?
1.调用的qml封装文件不在当前目录或者子目录时候,直接引入路径:
import "qrc:/qml"
四、qml中Quick 1.0库和Quick 2.0库如何同时引用?
1.相当于c++中作用域的使用
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls 1.2 as Controls1_2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log("ssss "+Qt.application.arguments[0])
}
Image {
id: name
source: "qrc:/image/test.png"
}
Controls1_2.Button{
id: name1
text: "测试quick 1.0 Button"
}
}
总结
这些东西比较乱,在此整理下,希望帮助到大家。