Skip to content

Instantly share code, notes, and snippets.

@davidlatwe
Created February 4, 2020 19:28
Show Gist options
  • Save davidlatwe/44d6236570a11ebb869682a8d0b4f661 to your computer and use it in GitHub Desktop.
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
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_()
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.
}
@davidlatwe
Copy link
Author

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