Skip to content

Instantly share code, notes, and snippets.

@tim37021
Last active April 5, 2020 13:04
Show Gist options
  • Save tim37021/0f0decb68ba3d7183f840c5b0065cf43 to your computer and use it in GitHub Desktop.
Save tim37021/0f0decb68ba3d7183f840c5b0065cf43 to your computer and use it in GitHub Desktop.
PyQT5 recreate qml object that references the same python object
import sys
from PyQt5.QtQml import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class ClassA(QObject):
bChanged = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self._b = None
@pyqtProperty(QObject, notify=bChanged)
def b(self):
return self._b
@b.setter
def b(self, val):
self._b = val
self.bChanged.emit()
class ClassB(QObject):
def __init__(self, parent=None):
super().__init__(parent)
@pyqtSlot(QObject, result=bool)
def equal(self, ref):
return self == ref
def runQML():
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
QApplication.setAttribute(Qt.AA_UseDesktopOpenGL)
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
qmlRegisterType(ClassA, 'CustomClass', 1, 0, 'ClassA')
qmlRegisterType(ClassB, 'CustomClass', 1, 0, 'ClassB')
engine.load('test2.qml')
if not engine.rootObjects():
return -1
return app.exec_()
if __name__ == "__main__":
sys.exit(runQML())
import QtQuick 2.12
import QtQuick.Controls 2.12
import CustomClass 1.0
ApplicationWindow {
width: 800
height: 600
visible: true
ClassA {
b: ClassB {
id: bb
}
Component.onCompleted: {
console.log('test 1:'+(this.b==bb).toString())
console.log('test 2:'+(this.b.equal(bb)).toString())
}
}
ClassA {
b: Rectangle {
id: rec
}
Component.onCompleted: {
console.log('test 3:'+(this.b==rec).toString())
}
}
}
@tim37021
Copy link
Author

tim37021 commented Apr 5, 2020

STDOUT:

qml: test 3:true
qml: test 1:false
qml: test 2:true

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