下拉列表框样式如图:
字体列表框样式:
1 import sys 2 from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QFontComboBox, QLineEdit, QMessageBox, QVBoxLayout 3 import time 4 5 class Demo(QWidget): 6 choice = 'a' 7 choice_list = ['b', 'c', 'd', 'e'] 8 9 def __init__(self): 10 super(Demo, self).__init__() 11 12 self.combobox_1 = QComboBox(self) # 实例化下拉列表框 13 self.combobox_2 = QFontComboBox(self) # 实例化字体列表框 14 15 self.lineedit = QLineEdit(self) 16 17 self.v_layout = QVBoxLayout() 18 19 self.layout_init() 20 self.combobox_init() 21 22 23 def layout_init(self): 24 self.v_layout.addWidget(self.combobox_1) 25 self.v_layout.addWidget(self.combobox_2) 26 self.v_layout.addWidget(self.lineedit) 27 28 self.setLayout(self.v_layout) 29 30 def combobox_init(self): 31 self.combobox_1.addItem(self.choice) # 添加一个选项 32 self.combobox_1.addItems(self.choice_list) # 添加容器中的参数。容器:可迭代的 33 self.combobox_1.currentIndexChanged.connect(lambda: self.on_combobox_func(self.combobox_1)) 34 #选项发生变化时发出信号 35 # self.combobox_1.currentTextChanged.connect(lambda: self.on_combobox_func(self.combobox_1)) 36 #当文本内容发生变化时发出信号 37 38 self.combobox_2.currentFontChanged.connect(lambda: self.on_combobox_func(self.combobox_2)) 39 #字体选项发生变化时发出信号 40 41 def on_combobox_func(self, combobox): 42 if combobox == self.combobox_1: 43 QMessageBox.information(self, 'ComboBox 1', 44 '{}: {}'.format(combobox.currentIndex(), combobox.currentText())) 45 #combobox.currentIndex() 返回当前索引号 46 #combobox.currentText() 返回当前选项的文本 47 else: 48 self.lineedit.setFont(combobox.currentFont()) 49 #单行文本编辑框设置字体 50 #combobox.currentFont() 字体选择框中当前的字体 51 52 53 54 if __name__ == '__main__': 55 app = QApplication(sys.argv) 56 demo = Demo() 57 demo.show() 58 sys.exit(app.exec_())