PySide6 Property notify signal emit automatically
-
I need clarification about PySide6 Property class. The documentation says
"The signal is emitted automatically when the property is changed via the Qt API ( setProperty , QMetaProperty , etc.), but not when the MEMBER is changed directly." here and here
I am unable to replicate what that sentence says in PySide6. For testing purposes I subclassed
QLabel
and added my class a property with a corresponding signal. But the signal is only emitted when I do it manually (ie. when I useself.bgColorChanged.emit()
) whether I usesetBgColor
orsetProperty
.So I either do not understand what the quoted sentence means or I'am doing something wrong in my code.
Here is the full code
import sys import random from PySide6.QtCore import Property, Signal from PySide6.QtWidgets import (QApplication, QWidget, QLabel, QPushButton, QVBoxLayout) class StyledLabel(QLabel): _bg_color = 'lightgreen' bgColorChanged = Signal() def bgColor(self): return self._bg_color def setBgColor(self, bg_color): self._bg_color = bg_color self.setStyleSheet( f'StyledLabel {{ background-color: {self.bgColor}}}') # self.bgColorChanged.emit() bgColor = Property( str, fget=bgColor, fset=setBgColor, notify=bgColorChanged) class Window(QWidget): colors = ['darkCyan', 'darkYellow', 'darkGrey', 'cyan', 'yellow', 'gray', 'orange', 'teal'] def __init__(self): super().__init__() layout = QVBoxLayout() self.setLayout(layout) button = QPushButton('Change label color') button.clicked.connect(self.on_button_clicked) layout.addWidget(button) self.label = StyledLabel('Label with style') self.label.setBgColor('lightsteelblue') self.label.bgColorChanged.connect(self.on_bgcolor_changed) layout.addWidget(self.label) def on_button_clicked(self): # self.label.setBgColor(random.choice(self.colors)) self.label.setProperty('bgColor', random.choice(self.colors)) def on_bgcolor_changed(self): print('Background color changed') if __name__ == '__main__': if not QApplication.instance(): app = QApplication(sys.argv) else: app = QApplication.instance() main_window = Window() main_window.show() sys.exit(app.exec())
-
Hi,
As the example code shows in the document you link, the signal is emitted explicitly when a change occurs.
You have to code it yourself. -
Hi,
As the example code shows in the document you link, the signal is emitted explicitly when a change occurs.
You have to code it yourself.@SGaist Thank you
-