下拉列表框
一、效果展示二、相关控件0.头文件1.QLabel()2.QPushButton()3.QComboBox() 三、源代码一、效果展示
二、相关控件
0.头文件
import PyQt5.QtWidgets as qtwimport PyQt5.QtGui as qtg
1.QLabel()
创建标签控件:
my_label = qtw.QLabel("Hello World!")
改变标签内容:
my_label.setText("Hello World!")
2.QPushButton()
创建按钮并添加按钮点击事件:
my_button = qtw.QPushButton("Press Me!", clicked=lambda: press_it())def press_it():my_label.setText("What's your name?")
3.QComboBox()
给combox增加元素
my_combo.addItem("English", 50)my_combo.addItem("Math", 40)my_combo.addItem("Chinese", 100)my_combo.addItem("Science", 30)
获取下拉列表的元素:
my_combo.currentText()
获取下拉列表元素对应的值:
my_combo.currentData()
三、源代码
import PyQt5.QtWidgets as qtwimport PyQt5.QtGui as qtgclass MainWindow(qtw.QWidget):def __init__(self):super(MainWindow, self).__init__()self.setWindowTitle("Hello PyQt5!")# 建立一个垂直容器self.setLayout(qtw.QVBoxLayout())my_label = qtw.QLabel("Hello World!")my_label.setFont(qtg.QFont('Heletica', 18))self.layout().addWidget(my_label) # 将标签添加到容器中# 创建一个ComboxBoxmy_combo = qtw.QComboBox(self)# 给combox增加元素my_combo.addItem("English", 50)my_combo.addItem("Math", 40)my_combo.addItem("Chinese", 100)my_combo.addItem("Science", 30)# 将comboBox添加到容器中self.layout().addWidget(my_combo)# 创建一个按钮my_button = qtw.QPushButton("Press Me!", clicked=lambda: press_it())# 将按钮添加到容器中self.layout().addWidget(my_button)self.show()def press_it():my_label.setText(f'You clicked {my_combo.currentText()},the value is {my_combo.currentData()}!')if __name__ == '__main__':app = qtw.QApplication([])w = MainWindow()app.exec_()
如果觉得《极速PyQt5基础教程02:ComboBox【下拉列表框】》对你有帮助,请点赞、收藏,并留下你的观点哦!