如何正确地在两个不同的对象(类)之间连接pyqtSignal
?我的意思是最佳实践。
了解我为实现目标所做的工作:Thermometer
类会在Pot
温度升高时收到通知:
from PyQt4 import QtCore
class Pot(QtCore.QObject):
temperatureRaisedSignal = QtCore.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()
或者有更简单/更好的方法吗?
我也坚持(如果可能的话)使用“新”式PyQt信号。
答案 0 :(得分:21)
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()
这就是我根据文档完成它的方式:
http://www.riverbankcomputing.com/static/Docs/PyQt4/html/new_style_signals_slots.html