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);
#endif
QGuiApplication 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.15
QtObject {
id: root
property QtObject $splashScreen: Splash{}
property var loader: Loader{
asynchronous: true
source: "qrc:/MainView.qml"
active: false
onLoaded: {
$splashScreen.delay();
}
}
Component.onCompleted:{
loader.active = true;
}
}
3.3 MainView.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
id: window
visible: true
width: 800
height: 600
title: qsTr("Splash Demo")
flags: Qt.Window | Qt.FramelessWindowHint
Button{
anchors{
top: parent.top;
right: parent.right;
margins: 5
}
text: "X"
width: 50
height: 50
onClicked: Qt.quit();
}
Text{
text: qsTr("Test window");
anchors.centerIn: parent
font.pointSize: 30
}
Component.onCompleted: window.show()
}
3.4 Splash.qml
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
id: splash
color: "transparent"
title: "Splash Window"
modality: Qt.ApplicationModal
flags: Qt.SplashScreen | Qt.WindowStaysOnTopHint
x: (Screen.width - splashImage.width) / 2
y: (Screen.height - splashImage.height) / 2
width: splashImage.width
height: splashImage.height
Image {
id: splashImage
source: "qrc:/background.png"
}
Text{
id: textCtrl
width: contentWidth
height: contentHeight
anchors{
left: splashImage.left;
bottom: splashImage.bottom
}
font.pointSize: 30
}
Timer {
id: timer
interval: 1000;
running: false;
repeat: false
onTriggered: {
splash.visible = false;
}
}
Component.onCompleted: {
splash.show()
}
function delay(){
timer.start();
}
}