PyQt5实现 当下拉列表中的选项改变时,标签的文本更新
上效果:
上代码:
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QComboBox, QVBoxLayout
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.lb01 = QLabel(self)
self.lb01.setGeometry(300, 300, 100, 100)
self.lb01.setText("类别:")
self.lb01.setFont(QFont("Adobe Heiti Std", 10))
self.cb02 = QComboBox(self)
self.cb02.setGeometry(90, 50, 130, 20)
self.cb02.addItems(['A', 'B'])
# 连接 QComboBox 的 currentIndexChanged 信号到 update_label 槽函数
self.cb02.currentIndexChanged.connect(self.update_label)
# 初始化标签的文本,以反映当前选中的项
self.update_label(self.cb02.currentIndex())
# 设置布局(可选,但推荐用于管理组件)
layout = QVBoxLayout()
layout.addWidget(self.lb01)
layout.addWidget(self.cb02)
self.setLayout(layout)
self.setWindowTitle('ComboBox 和 Label 示例')
self.show()
def update_label(self, index):
print(index)
# 获取当前选中的文本
text = self.cb02.currentText()
# 更新标签的文本
self.lb01.setText(f"类别:{text}")
# 主函数
if __name__ == '__main__':
app = QApplication([])
ex = MyWidget()
app.exec_()