PyQt5中的事件和信号

来源:互联网 发布:linux squid 编辑:程序博客网 时间:2024/05/21 11:34

PyQt5中的Events和signals

这部分教程中,探讨应用中的时间和信号。

Events

GUI应用是event驱动的。event主要有用户产生,但也可能由其他产生,比如一个内部连接、一个窗口管理者、一个定时器。但调用应用的exec_()方法,应用进入主循环。主循环取得event并传给对象.
event模型有三个要素:

  • 事件源
  • 事件对象
  • 事件目标

事件源:是一个对象,当其状态发生改变时产生event
事件对象:封装了事件源的状态改变
事件目标:被通知对象

事件对象代表一个 事件目标要处理的任务

PyQt5有一个独特的sinal(信号)和slot(槽)的机制来处理vent。signals和slots用来对象间的通信。一个event发生会发出signal。slot可以是任何python的callable(这里有待进一步理解)。当所连接的信号发生slot就会被调用。

Signals he slots

下面是一个演示signals和slots的例子

#we connect a signal of a QSlider to a slot of a QLCDNumber. import sysfrom PyQt5.QtCore import Qtfrom PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider,     QVBoxLayout, QApplication)class Example(QWidget):    def __init__(self):        super().__init__()        self.initUI()    def initUI(self):        lcd = QLCDNumber(self)        sld = QSlider(Qt.Horizontal, self)        vbox = QVBoxLayout()        vbox.addWidget(lcd)        vbox.addWidget(sld)        self.setLayout(vbox)        sld.valueChanged.connect(lcd.display)        self.setGeometry(300, 300, 250, 150)        self.setWindowTitle('Signal and slot')        self.show()if __name__ == '__main__':    app = QApplication(sys.argv)    ex = Example()    sys.exit(app.exec_())

例子中,显示了一个QtGui.QLCDNumberQtGui.QSlider。通过拖拽slider控件来改变lcd的显示

sld.valueChanged.connect(lcd.display)

这里,我们连接一个 slider控件valurChanged 信号 到 lcd控件display槽。
发送者是 发送信号的对象,接受者是 接受信号的对象,槽是 响应信号的方法。
signal&slot

重新实现事件处理函数

#In this example, we reimplement an event handler.import sysfrom PyQt5.QtCore import Qtfrom PyQt5.QtWidgets import QWidget, QApplicationclass Example(QWidget):    def __init__(self):        super().__init__()        self.initUI()    def initUI(self):              self.setGeometry(300, 300, 250, 150)        self.setWindowTitle('Event handler')        self.show()    def keyPressEvent(self, e):        if e.key() == Qt.Key_Escape:            self.close()if __name__ == '__main__':    app = QApplication(sys.argv)    ex = Example()    sys.exit(app.exec_())

例子中,重新实现了keyPressEvent()时间处理函数

def keyPressEvent(self, e):    if e.key() == Qt.Key_Escape:        self.close()

点击escape键,退出应用

Event object(事件对象)

事件对象是一个python对象,他包含一个用来描述时间属性的数值。事件对象特定于生成的时间类型。

#In this example, we display the x and y coordinates of a mouse pointer in a label widget.import sysfrom PyQt5.QtCore import Qtfrom PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLabelclass Example(QWidget):    def __init__(self):        super().__init__()        self.initUI()    def initUI(self):              grid = QGridLayout()        grid.setSpacing(10)        x = 0        y = 0        self.text = "x: {0},  y: {1}".format(x, y)        self.label = QLabel(self.text, self)        grid.addWidget(self.label, 0, 0, Qt.AlignTop)        self.setMouseTracking(True)        self.setLayout(grid)        self.setGeometry(300, 300, 350, 200)        self.setWindowTitle('Event object')        self.show()    def mouseMoveEvent(self, e):        x = e.x()        y = e.y()        text = "x: {0},  y: {1}".format(x, y)        self.label.setText(text)if __name__ == '__main__':    app = QApplication(sys.argv)    ex = Example()    sys.exit(app.exec_())

例子中,用label控件显示鼠标点的坐标

self.text = "x: {0},  y: {1}".format(x, y)self.label = QLabel(self.text, self)

label控件用来显示坐标

self.setMouseTracking(True)

默认没有开启鼠标追踪,所以只有在移动中的鼠标点击时,才会接收到移动事件。如果鼠标追踪开启,即使没有点击鼠标也可以接收到移动事件。

def mouseMoveEvent(self, e):    x = e.x()    y = e.y()    text = "x: {0},  y: {1}".format(x, y)    self.label.setText(text)

这个e是事件对象,它包含事件被触发时的数据,例子中,它是鼠标移动事件。
x()y()方法确定鼠标的x、y坐标。
event object

事件发送者

控件是信号的发送者,基于此,PyQt5有sender()方法

#we determine the event sender objectimport sysfrom PyQt5.QtWidgets import QMainWindow, QPushButton, QApplicationclass Example(QMainWindow):    def __init__(self):        super().__init__()        self.initUI()    def initUI(self):              btn1 = QPushButton("Button 1", self)        btn1.move(30, 50)        btn2 = QPushButton("Button 2", self)        btn2.move(150, 50)        btn1.clicked.connect(self.buttonClicked)                    btn2.clicked.connect(self.buttonClicked)        self.statusBar()        self.setGeometry(300, 300, 290, 150)        self.setWindowTitle('Event sender')        self.show()    def buttonClicked(self):        sender = self.sender()        self.statusBar().showMessage(sender.text() + ' was pressed')if __name__ == '__main__':    app = QApplication(sys.argv)    ex = Example()    sys.exit(app.exec_())

例子中有2个按键。在buttonClicked()方法中决定是哪个按键点击了通过调用sender()方法

btn1.clicked.connect(self.buttonClicked)            btn2.clicked.connect(self.buttonClicked)

2个按键被连接到相同的槽

def buttonClicked(self):    sender = self.sender()    self.statusBar().showMessage(sender.text() + ' was pressed')

通过调用sender()方法决定信号源。应用状态栏中显示按下的按键的label
event sender

发出信号

QOjbect创建的对象可以发射信号
以下例子展示如何发送自定义信号

#we show how to emit a custom signal. import sysfrom PyQt5.QtCore import pyqtSignal, QObjectfrom PyQt5.QtWidgets import QMainWindow, QApplicationclass Communicate(QObject):    closeApp = pyqtSignal() class Example(QMainWindow):    def __init__(self):        super().__init__()        self.initUI()    def initUI(self):              self.c = Communicate()        self.c.closeApp.connect(self.close)               self.setGeometry(300, 300, 290, 150)        self.setWindowTitle('Emit signal')        self.show()    def mousePressEvent(self, event):        self.c.closeApp.emit()if __name__ == '__main__':    app = QApplication(sys.argv)    ex = Example()    sys.exit(app.exec_())

创建了一个叫做closeApp的信号。这个信号连接到QMainWindowclose()

class Communicate(QObject):    closeApp = pyqtSignal()   

pyqtSignal()创建信号,并作为Communicate类的属性

self.c = Communicate()self.c.closeApp.connect(self.close) 

自定义信号closeApp连接到QMainWindowclose()

def mousePressEvent(self, event):    self.c.closeApp.emit()

当在应用窗口内点击鼠标,closeApp信号被发送,结束应用

原文在此

原创粉丝点击