QPushButton控件和QRadioButton控件案例
import sys
from PyQt5.QtCore import Qt, QRegExp
from PyQt5.QtGui import QIcon, QFont, QPalette, QPixmap, QIntValidator, QDoubleValidator, QRegExpValidator
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QToolTip, QHBoxLayout, QMainWindow, QLabel, QVBoxLayout, \
QDialog, QLineEdit, QGridLayout, QFormLayout, QTextEdit, QRadioButton
'''
按钮控件 QPushButton 控件的案例
QAbstractButton
QPushButton
AToolButton
QRadioButton
QCheckBox
'''
class QPushButtonDemo(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 设置定位和左上角坐标
self.setGeometry(300, 300, 400, 250)
# 设置窗口标题
self.setWindowTitle('QPushButton控件的演示')
# 设置窗口图标
# self.setWindowIcon(QIcon('../web.ico'))
# 创建表单布局
vLayout = QVBoxLayout()
# 创建控件
self.button1 = QPushButton('按钮1')
# self.button1.setText('First Button')
self.button1.setCheckable(True)
self.button1.toggle()
vLayout.addWidget(self.button1)
self.button1.clicked.connect(self.buttonState)
self.button1.clicked.connect(lambda:self.whichButton(self.button1))
# 在文本前面显示图像
self.button2 = QPushButton('图像按钮')
self.button2.setIcon(QIcon(QPixmap('../web.ico')))
self.button2.clicked.connect(lambda :self.whichButton(self.button2))
vLayout.addWidget(self.button2)
# 不可用按钮
self.button3 = QPushButton('不可用按钮')
self.button3.setEnabled(False)
self.button3.clicked.connect(lambda: self.whichButton(self.button3))
vLayout.addWidget(self.button3)
# 不可用按钮
self.button4 = QPushButton('&My Button 按钮')
self.button4.setDefault(True)
self.button4.clicked.connect(lambda: self.whichButton(self.button4))
vLayout.addWidget(self.button4)
# 单选按钮
self.button5 = QRadioButton('单选按钮1')
self.button5.setChecked(True)
self.button5.toggled.connect(self.buttonStateRadio)
vLayout.addWidget(self.button5)
# 单选按钮
self.button6 = QRadioButton('单选按钮2')
# self.button6.setChecked(True)
self.button6.toggled.connect(self.buttonStateRadio)
vLayout.addWidget(self.button6)
self.setLayout(vLayout)
def whichButton(self,btn):
print("被单击的按钮是<"+btn.text()+">")
def buttonState(self):
if self.button1.isChecked():
print("按钮1被选中")
else:
print("按钮1没有被选中!")
def buttonStateRadio(self):
radioButton = self.sender()
if radioButton.text() == '单选按钮1':
if radioButton.isChecked():
print("<"+radioButton.text()+">被选中")
else:
print("<"+radioButton.text()+">没有被选中")
if radioButton.text() == '单选按钮2':
if radioButton.isChecked():
print("<" + radioButton.text() + ">被选中")
else:
print("<" + radioButton.text() + ">没有被选中")
if __name__ == '__main__':
app = QApplication(sys.argv)
# 设置应用图标
app.setWindowIcon(QIcon('../web.ico'))
w = QPushButtonDemo()
w.show()
sys.exit(app.exec_())