PyQt5的学习之路(五)

时间:2022-04-22 08:35:14

信号&槽机制

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

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLCDNumber, QSlider, QVBoxLayout
from PyQt5.QtCore import Qt

class Myform(QWidget):

def __init__(self):

super(QWidget, self).__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)

# signal & slot:当拖动条的值改变触发事件(值显示到数字板上)
# 信号(事件源) 槽(事件对象) 事件目标
sld.valueChanged.connect(lcd.display)

self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('signalslot')
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())

事件重写

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

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt

class Myform(QWidget):

def __init__(self):

super(Myform, self).__init__()
self.initUI()

def initUI(self):

self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('reimplement')
self.show()

# 重写了KeyPressEvent事件函数
def keyPressEvent(self, e):

# 当按下键盘上的'q'时,程序退出
if e.key() == Qt.Key_Q:
self.close()

if __name__ == '__main__':

app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())

事件发送者

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

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QVBoxLayout, QHBoxLayout


class Myform(QMainWindow):

def __init__(self):

super(Myform, self).__init__()
self.initUI()

def initUI(self):

btn1 = QPushButton('Button1', self)
btn2 = QPushButton('Button2', self)

# 为按钮添加点击事件
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)

hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(btn1)
hbox.addWidget(btn2)

vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)

widget = QWidget()
widget.setLayout(vbox)
self.setCentralWidget(widget) # QMainWindow有自己的布局了,所以不能直接setLayout


self.resize(300, 200)
self.move(300, 300)
self.setWindowTitle('sender')
self.show()

self.statusBar()

def buttonClicked(self):

# 事件: 显示信号发出者
sender = self.sender()
self.statusBar().showMessage(sender.text() + ' was pressed')

if __name__ == '__main__':

app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())

事件发送

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

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import pyqtSignal, QObject

# 定义新事件类
class Communicate(QObject):

closeApp = pyqtSignal()

class Myform(QMainWindow):

def __init__(self):

super(Myform, self).__init__()
self.initUI()

def initUI(self):

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

self.move(300, 300)
self.resize(300, 200)
self.setWindowTitle('emitsignal')
self.show()

# 事件传递
def mousePressEvent(self, event):

self.c.closeApp.emit()

if __name__ == '__main__':

app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())