这是一个示例from an video tutorial:
#!/usr/bin/env python3
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class ZeroSpinBox(QSpinBox):
zeros = 0
def __init__(self):
super().__init__()
self.valueChanged.connect(self.checkzero)
def checkzero(self):
if self.value() == 0:
self.zeros += 1
self.emit(SIGNAL("atzero(int)"), self.zeros)
class Form(QDialog):
def __init__(self):
super().__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_()
请注意,我为zerospinbox对象建立了两个连接,第一个使用新的连接语法,第二个使用旧语法。还有一行用于使用新语法进行相同的第二次连接,但它不起作用,因此它被注释掉了。 atzero信号是定制的,似乎信号使得这对新语法不起作用。这是由于排放方法吗?如何将新语法应用于atzero信号呢?
答案 0 :(得分:5)
您必须在课程中声明您已实施或继承的新信号;
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_()