我正在阅读“Rapid Gui Programming with Python and Qt”一书,但在信号/槽项目上遇到了问题。我已经下载了作者的代码与我自己的代码进行比较,它们看起来都一样,但是,当我从派生的旋转框类发出信号时,python 就崩溃了。这是我的全部代码:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class ZeroSpinBox(QSpinBox):
zeros = 0
def __init__(self, parent=None):
super(ZeroSpinBox, self).__init__(parent)
self.connect(self, SIGNAL("valueChanged(int)"), self.checkzero)
def checkzero(self):
if self.value() == 0:
self.zeros += 1
self.emit(SIGNAL("atzero"), self.zeros)
class Form(QDialog):
def __init__(self, parent= None):
super(Form, self).__init__(parent)
dial = QDial()
dial.setNotchesVisible(True)
spinbox = ZeroSpinBox()
spinbox.setRange(0,200)
dial.setRange(0,200)
layout = QHBoxLayout()
layout.addWidget(dial)
layout.addWidget(spinbox)
self.setLayout(layout)
self.connect(dial, SIGNAL("valueChanged(int)"), spinbox, SLOT("setValue(int)"))
self.connect(spinbox, SIGNAL("valueChanged(int)"), dial, SLOT("setValue(int)"))
self.connect(spinbox, SIGNAL("atzero"), self.announce)
self.setWindowTitle("Signals and Slots Part 2")
def announce(self, zeros):
print "ZeroSpinBox has been at zero %d times" % zeros
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
当旋转框降为零时,我的问题出现了,checkzero(self) 方法(属于 ZeroSpinBox 类)被调用,self.zeros += 1 行正常,然后在发射行上 windows 报告 Python. exe崩溃了。我得到的错误是“python.exe 已停止工作”并且控制台报告“进程已完成,退出代码为 -1073741819”
知道为什么会这样吗?这是带有 PySide 的 Python 2.7.2 和 PyQT4。
请您参考如下方法:
在 checkzero 和 Form 中用 ,因为您声明它的方式不包含任何参数。SIGNAL("atzero(int)") 替换 SIGNAL("atzero") .__init__
编辑:“新式”中的代码,
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class ZeroSpinBox(QSpinBox):
zeros = 0
def __init__(self, parent=None):
super(ZeroSpinBox, self).__init__(parent)
self.valueChanged.connect(self.checkzero)
atzero = Signal(int)
def checkzero(self):
if self.value() == 0:
self.zeros += 1
self.atzero.emit(self.zeros)
class Form(QDialog):
def __init__(self, parent= None):
super(Form, self).__init__(parent)
dial = QDial()
dial.setNotchesVisible(True)
spinbox = ZeroSpinBox()
spinbox.setRange(0,200)
dial.setRange(0,200)
layout = QHBoxLayout()
layout.addWidget(dial)
layout.addWidget(spinbox)
self.setLayout(layout)
dial.valueChanged.connect(spinbox.setValue)
spinbox.valueChanged.connect(dial.setValue)
spinbox.atzero.connect(self.announce)
self.setWindowTitle("Signals and Slots Part 2")
@Slot(int)
def announce(self, zeros):
print "ZeroSpinBox has been at zero %d times" % zeros
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
