PyQt4 tutorial读书笔记(4)-- events and signals

一、事件(events)

==》所有的gui应用都是事件驱动型,大部分事件产生是通过应用的用户,但是也可以是由其它方式产生。比如:网络连接,窗口管理,或者定时器。当我们调用application‘s exec_()函数,程序进入main loop。主循环获取事件并将它们发送给对象。

1、在一个事件模型里,有三个参与者

       *event source 事件源
       *event object
       *event target

2、信号与槽(signal and slot)机制

==》用于在多个对象中进行交流。
(1)A slot is called when a signal connected to it is emitted.

    #!/usr/bin/python
# -*- coding: utf-8 -*-

""" ZetCode PyQt4 tutorial In this example, we connect a signal of a QtGui.QSlider to a slot of a QtGui.QLCDNumber. author: Jan Bodnar website: zetcode.com last edited: October 2011 """

import sys
from PyQt4 import QtGui, QtCore


class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        lcd = QtGui.QLCDNumber(self)
        sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(lcd)
        vbox.addWidget(sld)

        self.setLayout(vbox)
        sld.valueChanged.connect(lcd.display)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Signal & slot')
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

(2)重写事件处理函数:

import sys
from PyQt4 import QtGui, QtCore


class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__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() == QtCore.Qt.Key_Escape:
            self.close()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

例子中重写了keyPressEvent()事件处理函数。
(3)事件sender
非常便捷的知道哪个控件是信号的发送者。通过sender()方法。

sender = self.sender()
sender.text() ##获取控件的text

3、发送信号

Objects created from a QtCore.QObject can emit(发出) signals. In the following example we will see how we can emit custom signals.
从QtCore.QObject继承的对象也可以发送信号。

import sys
from PyQt4 import QtGui, QtCore


class Communicate(QtCore.QObject):

    closeApp = QtCore.pyqtSignal() 


class Example(QtGui.QMainWindow):

    def __init__(self):
        super(Example, self).__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()


def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

你可能感兴趣的:(PyQt4 tutorial读书笔记(4)-- events and signals)