开发者

How to connect pyqtSignal between classes in PyQT

开发者 https://www.devze.com 2023-01-19 11:16 出处:网络
How to connect pyqtSignal between two different objects (classes) PROPERLY? I mean best practice. Look what I have done to achieve the goal: The Thermometer class is notified when Pot increases its t

How to connect pyqtSignal between two different objects (classes) PROPERLY? I mean best practice.

Look what I have done to achieve the goal: The Thermometer class is notified when Pot increases its temperature:

from PyQt4 import QtCore

class Pot(QtCore.QObject):
    temperatureRaisedSignal = Q开发者_如何学JAVAtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(Pot, self).__init__(parent)
        self.temperature = 1
    def Boil(self):
        self.temperature += 1
        self.temperatureRaisedSignal.emit()
    def RegisterSignal(self, obj):
        self.temperatureRaisedSignal.connect(obj)

class Thermometer():
    def __init__(self, pot):
        self.pot = pot
        self.pot.RegisterSignal(self.temperatureWarning)
    def StartMeasure(self):
        self.pot.Boil()
    def temperatureWarning(self):
        print("Too high temperature!")

if __name__ == '__main__':
    pot = Pot()
    th = Thermometer(pot)
    th.StartMeasure()

Or is there any easier / better way to do it?

I also insist (if possible) on using "new" style PyQt signals.


from PyQt4 import QtCore

class Pot(QtCore.QObject):

    temperatureRaisedSignal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        QtCore.QObject.__init__(self)
        self.temperature = 1

    def Boil(self):
        self.temperatureRaisedSignal.emit()
        self.temperature += 1

class Thermometer():
    def __init__(self, pot):
        self.pot = pot
        self.pot.temperatureRaisedSignal.connect(self.temperatureWarning)

    def StartMeasure(self):
        self.pot.Boil()

    def temperatureWarning(self):
        print("Too high temperature!")

if __name__ == '__main__':
    pot = Pot()
    th = Thermometer(pot)
    th.StartMeasure()

This is how I would've done it according to the docs:
http://www.riverbankcomputing.com/static/Docs/PyQt4/html/new_style_signals_slots.html

0

精彩评论

暂无评论...
验证码 换一张
取 消