QPushButton控件的作用
QpushButton控件的形状是长方形,控件上可以显示文本或者图标。通常用于单击该按钮执行一些命令,或者响应一些事件。常见的有“确认”“申请”“取消”“关闭”“是”“否”等按钮。
QPushButton控件常用的方法
QPushButton代码示例
# -*- coding: utf-8 -*- import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) layout = QVBoxLayout() self.btn1 = QPushButton("Button1") self.btn1.setCheckable(True) self.btn1.toggle() # 对于需要传参的函数,需要使用lambda表示 self.btn1.clicked.connect(lambda:self.whichbtn(self.btn1) ) self.btn1.clicked.connect(self.btnstate) layout.addWidget(self.btn1) self.btn2 = QPushButton('image') # 给按钮添加图标 self.btn2.setIcon(QIcon(QPixmap("./images/python.png"))) self.btn2.clicked.connect(lambda:self.whichbtn(self.btn2) ) layout.addWidget(self.btn2) self.btn3 = QPushButton("Disabled") # 仅用按钮 self.btn3.setEnabled(False) layout.addWidget(self.btn3) self.btn4= QPushButton("&Download") self.btn4.setDefault(True) self.btn4.clicked.connect(lambda:self.whichbtn(self.btn4)) layout.addWidget(self.btn4) self.setLayout(layout) self.setWindowTitle("Button demo") def btnstate(self): if self.btn1.isChecked(): print("button pressed" ) else: print("button released" ) def whichbtn(self,btn): print("clicked button is " + btn.text() ) if __name__ == '__main__': app = QApplication(sys.argv) btnDemo = Form() btnDemo.show() sys.exit(app.exec_())
运行结果: