1. 工程结构
2. 现象
3. 代码
3.1 main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endifQGuiApplication app(argc, argv);QQmlApplicationEngine engine;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();
}
3.2 main.qml
import QtQuick 2.15
import QtQuick.Window 2.15QtObject {id: rootproperty QtObject $splashScreen: Splash{}property var loader: Loader{asynchronous: truesource: "qrc:/MainView.qml"active: falseonLoaded: {$splashScreen.delay();}}Component.onCompleted:{loader.active = true;}
}
3.3 MainView.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15ApplicationWindow {id: windowvisible: truewidth: 800height: 600title: qsTr("Splash Demo")flags: Qt.Window | Qt.FramelessWindowHintButton{anchors{top: parent.top;right: parent.right;margins: 5}text: "X"width: 50height: 50onClicked: Qt.quit();}Text{text: qsTr("Test window");anchors.centerIn: parentfont.pointSize: 30}Component.onCompleted: window.show()
}
3.4 Splash.qml
import QtQuick 2.15
import QtQuick.Window 2.15Window {id: splashcolor: "transparent"title: "Splash Window"modality: Qt.ApplicationModalflags: Qt.SplashScreen | Qt.WindowStaysOnTopHintx: (Screen.width - splashImage.width) / 2y: (Screen.height - splashImage.height) / 2width: splashImage.widthheight: splashImage.heightImage {id: splashImagesource: "qrc:/background.png"}Text{id: textCtrlwidth: contentWidthheight: contentHeightanchors{left: splashImage.left;bottom: splashImage.bottom}font.pointSize: 30}Timer {id: timerinterval: 1000;running: false;repeat: falseonTriggered: {splash.visible = false;}}Component.onCompleted: {splash.show()}function delay(){timer.start();}
}
4. 参考
- 纯QML添加Splash Screen的正确姿势