Use Signal in PySide or PyQt
-
class MyLabel(QLabel): updateSignal = Signal(str) def __init__(self): super().__init__() self.updateSignal.connect(self.updateText) def updateText(self, text: str): self.setText(text) class Window(QWidget): def __init__(self): super().__init__() self.label = MyLabel() self.label.setParent(self) # use Signal self.label.updateSignal.emit('go') # use MyLabel obj function self.label.updateText('go')
These two are the same in use in my opinion,
And the second one could be a little faster,
Both in development and in performance.- self.label.updateSignal.emit('go')
- self.label.updateText('go')
Or maybe I'm using the "Signa" l incorrectly.
If there are more nesting of "Widgets", then I will use an "object" to store the signaled object
class WidgetObject: Window1: Window class Window(QWidget): def __init__(self): super().__init__() ... WidgetObject.Window1 = self class Window2(QWidget): def __init__(self): super().__init__() def toWindow1LabelText(self): # use function WidgetObject.Window1.label.updateText('go2') # use signal WidgetObject.Window1.label.updateSignal.emit('go2')
So how should I use "Signal" better?
For more complex systems, how do I do the architecture, or as in the example above, use an "Object" to store the key "Widgets", I think this is too verboseThank you very much. I'm confused.
-
@jiajintao said in Use Signal in PySide or PyQt:
self.label.updateSignal.emit('go')
This makes no sence. Only the class where the signal is defined should emit it.
If Window needs to update something in MyLabel, then MyLabel should provide a method to do so:class MyLabel(QLabel): def __init__(self): super().__init__() def updateText(self, text: str): self.setText(text) class Window(QWidget): def __init__(self): super().__init__() self.label = MyLabel() self.label.setParent(self) self.label.updateText('go')
But this is also not needed in this case at all because MyLabel is already a QLabel and has setText method which can be called inside Window. So, I don't know what problem you're trying to solve...
-
@jiajintao
I don't know whether this will, help but....Your
def updateText(self, text: str):
is a public slot you have written. There are, effectively, always two ways a slot can be called:connect
a signal to call the slot, slot called when signal emitted; or- call the slot method directly, no signal/connection/emit.
This is just the case with slots, they are normal methods which can be called directly as well as via signals. Which way you invoke them depends on context, e.g. when within the slot class you might call the slot directly when required without going via signals. OTOH, the "outside world" is more likely to raise a signal when something happens, and you will have done a
connect
to have the slot called. This helps keep the distinction/independence between the slot class and the rest of the program, so outside world does not need to know much about slot class implementation. -