信号&槽机制
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)
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_())
事件重写
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()
def keyPressEvent(self, e):
if e.key() == Qt.Key_Q:
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())
事件发送者
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)
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_())
事件发送
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_())