您必须在您实现或继承的类中声明新信号;
class ZeroSpinBox (QSpinBox):
atzero = Signal(int)
.
.
然后,您可以在新式信号中调用它。用于发射信号;
self.emit(SIGNAL("atzero(int)"), self.zeros)
改成
self.atzero.emit(self.zeros)
用于连接信号;
self.connect(zerospinbox, SIGNAL("atzero(int)"), self.announce)
改成
zerospinbox.atzero.connect(self.announce)
您也可以阅读此内容document了解更多信息。
实现代码示例(PyQt4也相同PySide,不同的是名称Signal
& pyqtSignal
);
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class ZeroSpinBox(QSpinBox):
atzero = pyqtSignal(int)
zeros = 0
def __init__(self):
super(ZeroSpinBox, self).__init__()
self.valueChanged.connect(self.checkzero)
def checkzero(self):
if self.value() == 0:
self.zeros += 1
# self.emit(SIGNAL("atzero(int)"), self.zeros)
self.atzero.emit(self.zeros)
class Form(QDialog):
def __init__(self):
super(Form, self).__init__()
dial = QDial()
dial.setNotchesVisible(True)
zerospinbox = ZeroSpinBox()
layout = QHBoxLayout()
layout.addWidget(dial)
layout.addWidget(zerospinbox)
self.setLayout(layout)
dial.valueChanged.connect(zerospinbox.setValue)
zerospinbox.valueChanged.connect(dial.setValue)
zerospinbox.atzero.connect(self.announce)
# self.connect(zerospinbox, SIGNAL("atzero(int)"), self.announce)
self.setWindowTitle("Signals")
def announce(self, zeros):
print("zerospinbox has been at zero " + str(zeros) + " times.")
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()