欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-28 11:01:58
...

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_())


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