Skip to content

Instantly share code, notes, and snippets.

@akdasa
Last active November 13, 2022 18:48
Show Gist options
  • Save akdasa/495a3d7fda503c126a1bd7706723ff23 to your computer and use it in GitHub Desktop.
Save akdasa/495a3d7fda503c126a1bd7706723ff23 to your computer and use it in GitHub Desktop.
Create QML component dynamically from Python
import sys
from PyQt5.QtCore import QUrl, pyqtProperty, pyqtSignal
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtQml import qmlRegisterType, QQmlComponent
from PyQt5.QtQuick import QQuickItem
class Widget(QQuickItem):
def __init__(self, parent=None):
super().__init__(parent)
self._name = "Value"
print("New Widget handler created")
nameChanged = pyqtSignal()
@pyqtProperty('QString', notify=nameChanged)
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
self.nameChanged.emit()
@pyqtSlot(str, name="change")
def change(self, value):
print("Catched!!!!", value)
self.name = "Ch-ch-ch-changes! " + value
qmlRegisterType(Widget, 'MyWidgets', 1, 0, 'Widget')
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load("app.qml")
# get root (ApplicationWindow casted to QQuickItem)
root = engine.rootObjects()[0].children()[0]
# create component
component = QQmlComponent(engine)
component.loadUrl(QUrl("widget.qml"))
itm = component.create()
itm.setParentItem(root)
# fire and forget
sys.exit(app.exec_())
import QtQuick 2.5
import QtQuick.Controls 1.4
ApplicationWindow {
id: root
visible: true
width: 640
height: 480
}
import QtQuick 2.5
import MyWidgets 1.0
Widget {
id: self
Rectangle {
id: rect
color: "blue"
width: 100
height: 200
Text {
text: self.name
}
MouseArea {
anchors.fill: parent
onClicked: {
parent.color = 'green'
self.change("We gotcha click!")
}
}
}
}
@Dinosrules
Copy link

Awesome! You saved me some quality time after some hours or research. By any chance do you know how to set some properties for the qml components? For example if you want to position a qml at x: 70, how would that be specified in Python? Thank you in advance!

@mkhuzaima
Copy link

@Dinosrules You can use setContextProperty as described in the StackOverflow answer.

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