Created
February 4, 2020 19:28
-
-
Save davidlatwe/44d6236570a11ebb869682a8d0b4f661 to your computer and use it in GitHub Desktop.
Demonstrate how QQmlContext's property may be garbage collected before QML component gets destroyed and leads to "TypeError: Cannot read property 'foobar' of null" in PySide2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from PySide2 import QtCore, QtGui, QtQuick | |
class Data(QtCore.QObject): | |
color = QtCore.Property(str, fget=lambda _: "purple", constant=True) | |
if __name__ == '__main__': | |
class Application(QtGui.QGuiApplication): | |
def __init__(self): | |
super(Application, self).__init__(sys.argv) | |
window = QtQuick.QQuickView() | |
data = Data() # wrong, no parent. | |
# data = Data(parent=window) # correct | |
# ^^^ Uncomment above lines to compare the result on quit. | |
engine = window.engine() | |
engine.addImportPath(".") | |
context = engine.rootContext() | |
context.setContextProperty("DATA", data) | |
window.setSource(QtCore.QUrl.fromLocalFile("demo.qml")) | |
window.show() | |
self.window = window | |
# self.data = data | |
# ^^^ We could keep a reference here, but it still may die before QML, | |
# so the error will be random and hard to spot in this example. | |
app = Application() | |
app.exec_() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import QtQuick 2.0 | |
Rectangle { | |
anchors.fill: parent | |
color: DATA.color | |
// Will raise "TypeError: Cannot read property 'color' of null", | |
// if `DATA` has no parent assigned and become null object. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some references:
https://doc.qt.io/qt-5/qqmlcontext.html#details
https://wiki.qt.io/Defining-and-using-constants-from-PySide-in-QML