PyQt5基本窗口控件-----QPushButton

标签: pyqt学习  pyqt  gui  qt5

PyQt5学习之路,点击有pyqt5学习笔记
按钮的基类是QAbstractButton,该类为抽象类,不能实例化,必须由其他按钮类去继承。
常见的按钮类:

  • QPushButton:最普通辣个按钮
  • QToolButton: 工具条按钮
  • QRadioButton:单选按钮
  • QCheckBox:复选框
import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QPushButtonDemo(QDialog):
    def __init__(self):
        super(QPushButtonDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('QPushButtonDemo')
        self.resize(300, 200)

        layout = QVBoxLayout()

        self.button1 = QPushButton('第一个按钮')
        # 后期设置按钮文本内容
        self.button1.setText('First Button1')
        # 使button1处于选中的状态
        self.button1.setCheckable(True)
        # 开关按钮
        self.button1.toggle()
        self.button1.clicked.connect(self.buttonState)
        self.button1.clicked.connect(lambda :self.whichButton(self.button1))

        # 在文本前面显示图像
        self.button2 = QPushButton('图像按钮')
        self.button2.setIcon(QIcon(QPixmap('./about_us_bk.jpg')))
        self.button2.clicked.connect(lambda :self.whichButton(self.button2))

        # 不可用按钮
        self.button3 = QPushButton('不可用按钮')
        # 设置为不可用
        self.button3.setEnabled(False)

        # 设置按钮的默认状态
        self.button4 = QPushButton('&MyButton')
        # 设置按钮默认为按下,不理解就看图
        self.button4.setDefault(True)
        self.button4.clicked.connect(lambda :self.whichButton(self.button4))

        layout.addWidget(self.button1)
        layout.addWidget(self.button2)
        layout.addWidget(self.button3)
        layout.addWidget(self.button4)

        self.setLayout(layout)

    def whichButton(self, btn):
        print('被单击的按钮是<' + btn.text() + '>')

    def buttonState(self):
        if self.button1.isChecked():
            print('按钮1已经被选择')
        else:
            print('按钮1未被选中')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = QPushButtonDemo()
    main.show()
    sys.exit(app.exec_())


在这里插入图片描述

版权声明:本文为weixin_44653585原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_44653585/article/details/104474570