PyQt5基础学习-QPushButton按钮 1.设置选中翻转(QPushButton().toggle()) 2.在文本前显示图像 (QPushButton().setIcon) 3.设置按钮不可被选中(QPushButton().setEnabled(False)) 4.设置Enter输入点击按钮(QPushButton().setDefault(True)))5.lambda构造输入


在调用函数的时候,可能需要传入参数,因此使用lambda来构造函数进行传入

 self.button4.clicked.connect(lambda: self.whichButton(self.button4))

QPushButtonDemo.py 

"""
按钮控件 (QPushButton)

QAbstractButton

QPushButton
AToolButton
QRadioButton
QCheckBox
"""

import sys
from PyQt5.QtCore import *
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("QPushButton Demo")

        layout = QVBoxLayout()

        self.button1 = QPushButton("第一个按钮")
        self.button1.setText('First Button')
        #按第一次处于选中的状态
        self.button1.setCheckable(True)
        self.button1.toggle()
        self.button1.clicked.connect(lambda: self.whichButton(self.button1))
        self.button1.clicked.connect(self.buttonState)
        layout.addWidget(self.button1)

        # 在文本前面显示图像
        self.button2 = QPushButton('图像按钮')
        self.button2.setIcon(QIcon(QPixmap("D:\QTStudy\Picture\ic.png")))
        self.button2.clicked.connect(lambda: self.whichButton(self.button2))
        layout.addWidget(self.button2)
        
        #设置按钮为不可选中
        self.button3 = QPushButton("不可用的按钮")
        self.button3.setEnabled(False)
        layout.addWidget(self.button3)
        
        #按住Enter键时, 默认按住这个按钮
        self.button4 = QPushButton("&MyButton")
        self.button4.setDefault(True)
        self.button4.clicked.connect(lambda: self.whichButton(self.button4))

        layout.addWidget(self.button4)

        self.setLayout(layout)

        self.resize(400, 300)

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

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

if __name__ == "__main__":
    app = QApplication(sys.argv)

    main = QPushButtonDemo()
    main.show()

    sys.exit(app.exec_())

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM