Skip to content

Instantly share code, notes, and snippets.

@Siecje
Last active January 13, 2017 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Siecje/d1f2b270305762b4f73540c72adee6b8 to your computer and use it in GitHub Desktop.
Save Siecje/d1f2b270305762b4f73540c72adee6b8 to your computer and use it in GitHub Desktop.
Why does the setter run twice per instance
$ python whySetterMultipleTimes.py
<PyQt5.QtQml.QJSValue object at 0x7efd3eb4a978>
objectName: customType
names: ['one', 'two']
Times in setter: 1
<PyQt5.QtQml.QJSValue object at 0x7efd3eb4a978>
objectName: customType2
names: ['one', 'two']
Times in setter: 1
<PyQt5.QtQml.QJSValue object at 0x7efd3eb4a978>
objectName: customType
names: ['one', 'two']
Times in setter: 2
<PyQt5.QtQml.QJSValue object at 0x7efd3eb4a9e8>
objectName: customType2
names: ['one', 'two']
Times in setter: 2
$
import sys
from PyQt5 import QtCore, QtQml
from PyQt5.QtWidgets import QApplication
class CustomType(QtCore.QObject):
names_changed = QtCore.pyqtSignal()
def __init__(self, parent = None):
super().__init__(parent)
self._names = []
self._times_in_setter = 0
#@QtCore.pyqtProperty(QtQml.QJSValue, notify = names_changed)
#@QtCore.pyqtProperty(list, notify = names_changed)
@QtCore.pyqtProperty(QtCore.QVariant, notify = names_changed)
def names(self):
return self._names
@names.setter
def names(self, names):
print(names)
self._times_in_setter += 1
names_list = names.toVariant()
# if names_list == self._names:
# return
self._names = names_list
print("objectName: ", self.objectName())
print("names: ", self._names)
print("Times in setter: ", self._times_in_setter)
self.names_changed.emit()
print()
QML = b"""
import QtQuick 2.7
import QtQuick.Controls 1.4
import CustomType 1.0
ApplicationWindow {
visible: true
width: 800
height: 600
Column {
ComboBox {
model: customType.names
}
ComboBox {
model: customType2.names
}
}
CustomType {
id: customType
objectName: "customType"
names: ["one", "two"]
}
CustomType {
id: customType2
objectName: "customType2"
names: customType.names
}
}
"""
app = QApplication(sys.argv)
QtQml.qmlRegisterType(CustomType, 'CustomType', 1, 0, 'CustomType')
engine = QtQml.QQmlApplicationEngine()
engine.loadData(QML)
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment