五、常用控件(1)
因为常用控件较多我将常用分为了两部门进行总结,此处为第一部分。
5.1下拉框
下拉框在QT Designer中使用Combo Box控件来实现。如下图:
双击Combo Box控件,打开编辑页面,即可添加下拉框的内容,具体步骤如下图:
最终效果如图展示:
使用代码制作下拉框:
from PySide6.QtWidgets import QApplication, QWidget,QComboBox,QVBoxLayout
class MyWindow(QWidget):
def __init__(self):
super().__init__()
cb = QComboBox()
cb.addItems(['\0','张三','李四','王五']) # 添加元素,\0为空值
# cb.currentIndexChanged.connect(self.showName) # 获取信号,并且打印所选项序号,与下一行二选一
cb.currentTextChanged.connect(lambda: print(cb.currentText())) # 获取信号,并且打印所选项内容,与上一行二选一
mainlayout = QVBoxLayout() # 垂直控件
mainlayout.addWidget(cb) # 将cb导入到布局当中
self.setLayout(mainlayout) # 将该布局设置为当前窗口或小部件的布局
def showName(self,name):
print(name)
if __name__ == '__main__':
app = QApplication([])
window = MyWindow()
window.show()
app.exec()
实现效果如下:
5.2勾选框(多选框)
多选框在QT Designer中使用Check Box控件来实现,双击多选框旁边的字符即可编辑多选框字符。效果如下图:
使用代码制作多选框,并实现检测效果:
from PySide6.QtWidgets import QApplication, QWidget,QCheckBox,QVBoxLayout,QPushButton
class MyWindow(QWidget):
def __init__(self):
super().__init__()
cb = QCheckBox('是否被选中') # 创建多选框
cb.stateChanged.connect(self.showState)
btn = QPushButton('获取状态') # 创建按钮
btn.clicked.connect(lambda: print(cb.isChecked())) # 获取多选框状态
mainlayout = QVBoxLayout() # 垂直控件
# 将多选框和按钮放在窗体内
mainlayout.addWidget(cb)
mainlayout.addWidget(btn)
self.setLayout(mainlayout)
def showState(self,state):
print(state)
if __name__ == '__main__':
app = QApplication([])
window = MyWindow()
window.show()
app.exec()
实现效果:
当勾选框选中时命令行中弹出”2“,点击”获取状态时“弹出”True“
当勾选框没选中时命令行中弹出”0“,点击”获取状态时“弹出”False“
5.3 学生选择系统
学生选择系统所实现的功能是在多选框中选择学生姓名,并将学生姓名同步到下一级只读框内。勾选“是否确定”后在点击“选择完成”按钮时即可将姓名同步到再下一级只读框内,并做弹窗。若没有勾选即弹窗提醒。
from PySide6.QtWidgets import QApplication, QWidget,QMessageBox
from Ui_Student import Ui_Form
class MyWindow(QWidget,Ui_Form):
def __init__(self):
super().__init__()
self.setupUi(self) # 导入UI
# 当comboBox的当前索引改变时,直接更新lineEdit_Student的文本
self.comboBox.currentIndexChanged.connect(lambda index: self.lineEdit_Student.setText(self.comboBox.currentText()))
# 连接pushButton的clicked信号到on_pushButton_clicked槽函数
self.pushButton.clicked.connect(self.on_pushButton_clicked)
def on_pushButton_clicked(self):
# 检查checkBox是否被勾选
if not self.checkBox.isChecked():
# 如果未勾选,显示弹窗并打印消息
message_box = QMessageBox()
message_box.setWindowTitle("提示")
message_box.setText("请勾选是否确定")
message_box.setStandardButtons(QMessageBox.Ok)
message_box.exec() # 显示弹窗
else:
# 如果勾选,将lineEdit_Student中的文本复制到lineEdit_outcome中
self.lineEdit_outcome.setText(self.lineEdit_Student.text())
message_box = QMessageBox()
message_box.setWindowTitle("提示")
message_box.setText("选择完成!")
message_box.setStandardButtons(QMessageBox.Ok)
message_box.exec() # 显示弹窗
if __name__ == '__main__':
app = QApplication([])
window = MyWindow()
window.show()
app.exec()
运行截图:
勾选勾选框的运行截图
未勾选勾选框的运行截图