Skip to content

Instantly share code, notes, and snippets.

@mottosso
Last active February 18, 2023 08:24
Show Gist options
  • Save mottosso/fa01c80080363df3433d to your computer and use it in GitHub Desktop.
Save mottosso/fa01c80080363df3433d to your computer and use it in GitHub Desktop.
QML Reloading in PyQt5

Usage

git clone https://gist.github.com/fa01c80080363df3433d.git qmlreload
cd qmlreload
python main.py

Edit either SceneGraphEditor.qml or Viewport.qml and then hover it and hit F5 to reload.

# Based on this question on StackOverflow
# http://stackoverflow.com/questions/19604552/qml-loader-not-shows-changes-on-qml-file
import sys
from PyQt5 import QtQml, QtGui, QtCore
class ComponentCacheManager(QtCore.QObject):
def __init__(self, engine):
super(ComponentCacheManager, self).__init__()
self.engine = engine
@QtCore.pyqtSlot()
def trim(self):
self.engine.clearComponentCache()
if __name__ == '__main__':
app = QtGui.QGuiApplication(sys.argv)
engine = QtQml.QQmlApplicationEngine()
manager = ComponentCacheManager(engine)
context = engine.rootContext()
context.setContextProperty("componentCache", manager)
engine.load(QtCore.QUrl.fromLocalFile("main.qml"))
app.exec_()
import QtQuick 2.5
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
import QtQuick.Window 2.2
ApplicationWindow {
id: window
width: 300
height: 200
visible: true
title: "Feather 0.1"
Row {
id: sv
anchors.fill: parent
Loader {
property string path: "SceneGraphEditor.qml"
width: 150
height: 200
source: path
}
Loader {
property string path: "Viewport.qml"
width: 150
height: 200
source: path
}
}
MouseArea {
id: ma
anchors.fill: parent
hoverEnabled: true
}
Action {
shortcut: "F5"
onTriggered: {
var loader = sv.childAt(ma.mouseX, ma.mouseY);
print("Reloading ", loader.path);
loader.setSource("");
componentCache.trim();
loader.setSource(loader.path);
}
}
}
import QtQuick 2.5
Rectangle {
color: "purple"
}
import QtQuick 2.5
Rectangle {
color: "yellow"
}
@Fuhrmann
Copy link

Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment