pyqt5学习(1)自定义信号 博客分类: python pyqt5
程序员文章站
2024-02-23 11:59:04
...
pyqt5与老的pyqt4很多地方不一样,慢慢摸索.
qt使用信号和槽,这个叫法 蛮有意思的,不过原理和其它语言的差不多.
早上研究了下如何自定义信号并处理
书中(P95),原例是pyqt4,现环境是py3.5+pyqt5,我做了修改
左侧dial转动值,与右侧spinbox的值保持同步.另外,在dial中自定义过零刻度信号,指针到零刻度时发出信号.
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class ZeroSpinBox(QSpinBox): zeros = 0 atzero = pyqtSignal(int) #自定义信号,参数即在zeros,指针过零的次数 def __init__(self,parent=None): super(ZeroSpinBox,self).__init__(parent) self.valueChanged.connect(self.zerochk) #值改变,要检查 def zerochk(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) self.dial = QDial() self.dial.setNotchesVisible(True) self.spinbox = ZeroSpinBox() layout = QHBoxLayout() layout.addWidget(self.dial) layout.addWidget(self.spinbox) self.setLayout(layout) self.dial.valueChanged.connect(self.spinbox.setValue) self.spinbox.valueChanged.connect(self.dial.setValue) self.spinbox.atzero.connect(self.printzero) #这里处理自定义信号 def printzero(self,zerocount): #接受参数别忘了 print ("ZeroSpinBox has been at zero %d times"%zerocount) app = QApplication(sys.argv) form = Form() form.show() app.exec_()