pyqt信号与槽

import sys
from PyQt6.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
from PyQt6.QtCore import pyqtSlot


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 创建布局和按钮
        layout = QVBoxLayout()
        self.button = QPushButton('Click me')
        layout.addWidget(self.button)
        self.setLayout(layout)

        # 连接信号与槽
        self.button.clicked.connect(self.on_click)

    @pyqtSlot()
    def on_click(self):
        print('Button clicked!')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec())

案例:

testui.py
# Form implementation generated from reading ui file 'testui.ui'
#
# Created by: PyQt6 UI code generator 6.4.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt6 import QtCore, QtGui, QtWidgets


class Ui_Form(QtWidgets.QWidget):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(827, 701)
        self.pushButton = QtWidgets.QPushButton(parent=Form)
        self.pushButton.setGeometry(QtCore.QRect(240, 240, 311, 141))
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(parent=Form)
        self.label.setGeometry(QtCore.QRect(150, 100, 191, 61))
        self.label.setObjectName("label")
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "PushButton"))
        self.label.setText(_translate("Form", "测试"))

main.py

# Form implementation generated from reading ui file 'main.py'
#
# Created by: PyQt6 UI code generator 6.4.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.
from PyQt6.QtWidgets import QApplication, QWidget
from uitest.testui import Ui_Form
import sys
from PyQt6.QtCore import pyqtSlot


class MyWidget(Ui_Form):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)
        self.setupUi(self)  # 初始化界面
        # 连接信号与槽
        self.pushButton.clicked.connect(self.on_click)

    @pyqtSlot()  # 使用 pyqtSlot 装饰器标记槽函数
    def on_click(self):
        print("Button clicked!")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(app.exec())

你可能感兴趣的:(pyqt,python,开发语言)