How do I prevent my QML window from being shown until all the QML content is available?
In my example below an empty window is shown after QQmlApplicationEngine
is created, but the QML content doesn't appear until app.exec_()
is called. The effect is exaggerated with the time.sleep(1)
in my example code. The window is white, and then a second later it shows the red background.
What do I need to do so that all QML content is shown when the window appears? Or rather, how do I prevent the window from being shown until all the QML content is ready?
I am running on Windows.
QML
import QtQuick
import QtQuick.Controls
ApplicationWindow {
color: "red"
visible: true
}
Code
import time
from PySide6 import QtQml, QtWidgets
app = QtWidgets.QApplication([])
engine = QtQml.QQmlApplicationEngine("app_window.qml")
# This sleep exaggerates the issue so that you can easily observe
# that an empty window is shown by this point without QML content.
# Without the sleep the empty window looks like a white "flash"
# before the QML content is shown. I want to get rid of this "flash",
# so I don't want the empty window to ever be visible!
time.sleep(1)
app.exec_()
Here is a slow-mo recording of what I am seeing, at 1/8 speed playback, with no time.sleep()
. Note how the window is white when initially shown, and then it changes to red (well, my phone made it orange). I want the window to be red from the first instant that it is visible.
Widgets and QML are two distinct beasts in the land of Qt.
Normally, you should never mix the two in one project. Read more about the difference and concepts elsewhere.
QApplication Class is the way to instantiate a Qt Widgets application. Citing the docs:
QApplication specializes QGuiApplication with some functionality needed for QWidget-based applications. It handles widget specific initialization, finalization.
For QML applications, you go with a bare QGuiApplication and a QQmlEngine instances. It's important to realize that Qt app manages its lifecycle and event loop, while Qml engine is just like a yet another scripting engine on top of the app's event loop.
There are many moving parts in Qt ecosystem. I summarized my findings in one big XMind diagram in my Telegram blog. Check it out rendered.