QComboBox drop-down selection box
- Description
- It is a combined control, which displays the smallest space for the user to operate by default. You can select more preset options through the drop-down selection interface
- Inherited from: QWidget
- Functional role
- Constructor
QComboBox(parent: QWidget = None) # Create the QComboBox object and set the parent object at the same time
- Data operation
addItem(str, userData: Any = None) # Add an item, display content and background data addItem(QIcon, str, userData: Any = None) # Add an item, icon, display content and background data addItems(Iterable[str]) # add a batch of items through an iterator insertItem(int, str, userData: Any = None) # Insert an item at the specified index, display content and background data insertItem(int, QIcon, str, userData: Any = None) # Insert an item at the specified index, icon, display content and background data insertItems(int, Iterable[str]) # Add a batch of items at the specified index through an iterator setItemIcon(int, QIcon) # Set the icon of the item by index setItemText(int, str) # Through the index, set the display text of the item setItemData(int, Any, role: int = Qt.UserRole) # Set user data through index removeItem(int index) # delete the specified index item insertSeparator(int index) # Insert a separator line at the specified index position setCurrentIndex(int index) # Set the default display value of the drop-down box through the index setCurrentText(QString text) # Set the default display value of the drop-down box through the item display text setEditable(bool editable) # Set whether the default value can be edited # When it is allowed to be edited, press the Enter key after editing, and the edited new content will be added to the drop-down box setEditText(QString text) # When the default value setting can be edited, reset the display text content # Understand the model operation (we will talk about the model later) # By setting the model, the drop-down box can display tables, catalogs, etc. setModel(QAbstractItemModel model) setModelColumn(int visibleColumn) setRootModelIndex(QModelIndex index) model() modelColumn() rootModelIndex() # Learn about view operations setView(QAbstractItemView *itemView) view() # Learn about proxy settings setItemDelegate(QAbstractItemDelegate *delegate)
- Get data
count() -> int # Get the total number of items in the drop-down selection box itemIcon(int index) -> QIcon # Get the icon object of the specified index item itemText(int index) -> str # Get the text content of the specified index entry itemData(int index) -> Any # Get the user data of the specified index item currentIndex() -> int # Get the index of the currently selected item currentText() -> str # Get the text of the currently selected item currentDate() -> any # Get the user data of the currently selected item cb.itemIcon(cb.currentIndex()) # Use together to get the icon of the currently selected item
- Data limit
setMaxCount(int max) # Set the maximum number of storage entries. After reaching the maximum, it is not allowed to add, instead of deleting the old ones, add new ones maxCount() # Get the maximum number of storage entries setMaxVisibleItems(int maxItems) # Set the drop-down box to display the number of items on one screen, if there are too many items, a scroll bar will appear maxVisibleItems() # Get the number of items displayed in one screen of the drop-down box
- General operation
setEditable(bool editable) # Set whether the display box can be edited # When it is allowed to be edited, press the Enter key after editing, and the edited new content will be added to the drop-down box isEditable() # Get whether the display box can be edited setDuplicatesEnabled(bool enable) # Set whether to allow duplicate content to be appended to the drop-down box (when the input content is editable and press Enter) duplicatesEnabled() # Get whether to allow duplicate content to be appended to the drop-down box setFrame(bool) # Set whether to display the frame hasFrame() # Get whether to display the frame setIconSize(QSize(w, h)) # uniformly set icon size iconSize() # Get icon size setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy policy) # Set the drop-down box size adjustment policy # Parameter QComboBox. SizeAdjustPolicy QComboBox.AdjustToContents # The combo box will always be adjusted according to the content QComboBox.AdjustToContentsOnFirstShow # The combo box will adjust its content when it is first shown. QComboBox.AdjustToMinimumContentsLength # The combo box will be adjusted to the set minimum content length, please use AdjustToContents or AdjustToContentsOnFirstShow instead. QComboBox.AdjustToMinimumContentsLengthWithIcon # The combo box will adjust to the set minimum content length plus the space for the icon. For performance reasons, use this strategy on large models. sizeAdjustPolicy() -> QComboBox.SizeAdjustPolicy # Get the size adjustment policy of the drop-down box setMinimumContentsLength(int characters) # Set the minimum content length minimumContentsLength() -> int # Get the minimum content length
- Empty
clear() # Clear all stored entries clearEditText() # Clear the edited content in the combo box (clear the selected content)
- Popup
showPopup() # Pop up the drop-down box
- Completer (keyword completion effect)
setCompleter(QCompleter completer) # Set the completer completer() -> QCompleter to get the completer object
- validator
- For details, see: QValidator_validator object
setValidator(QValidator validator) # Set the validator # Pass in a QValidator object # Verify the input content by subclassing the QValidator class and rewriting the validator() and fixup() methods # validator() # get validator object
- Constructor
- Available signal
activated(int index) # When an item is selected (must be user interaction), this signal will be emitted only when the value changes, and the index of the selected item will be sent activated(QString text) # (overload) When an item is selected (must be user interaction), this signal will be emitted only when the value changes, and the display text of the selected item will be sent currentIndexChanged(int index) # When the currently selected index changes (user interaction, code control), send the index of the selected item currentIndexChanged(QString text) # (Overload) When the currently selected index changes (user interaction, code control), send the display text of the selected item currentTextChanged(QString text) # When the current text content changes, send new text content (including re-selecting the item and modifying the display text of the current item) editTextChanged(QString text) # In the editable state, when the edited text changes, send the new text content highlighted(int index) # When the highlight changes, send the index of the highlighted item (when the mouse is placed on it) highlighted(QString text) # (overload) When the highlight changes, send the display text of the highlighted item, when the mouse is placed on it textHighlighted(self, str) # When the display text highlight changes, send the display text of the highlighted item
- When the drop-down selection box object is in an editable state
- When modifying text content, trigger
currentTextChanged
andeditTextChanged
- After modifying the text content, press Enter to trigger
activated
andcurrentIndexChanged
- When modifying text content, trigger
- When the drop-down selection box object is in an editable state
QFontComboBox
- Description
- Font family selection drop-down selection box
- The combo box is populated with an alphabetical list of font family names, letting the user select a font family
- Later, you will learn the font selection dialog control: QFontDialog
- Inherited from: QComboBox
- Functional role
- Set and get the current font
setCurrentFont(QFont f) currentFont() -> QFont
- Set and get filters
setFontFilters(QFontComboBox.FontFilters) fontFilters() -> QFontComboBox.FontFilters # Parameter QFontComboBox.FontFilters QFontComboBox.AllFonts # Display all fonts QFontComboBox.ScalableFonts # Display scalable fonts QFontComboBox.NonScalableFonts # Display non-scalable fonts QFontComboBox.MonospacedFonts # Display monospaced fonts QFontComboBox.ProportionalFonts # Display proportional fonts
- Set and get the current font
- Signal
# inherit parent class currentIndexChanged(QString int) # Emit a signal when the current index changes, passing the entry index number currentIndexChanged(QString text) # (overload) emit a signal when the current index changes, and pass the item display content currentFontChanged(QFont font) # Emit a signal when the current font changes, passing a QFont object
- Code sample
- Example 1: QComboBox created using
from PyQt5.Qt import * import sys class Windows(QWidget): def __init__(self): super().__init__() self.setWindowTitle('QComboBox-create and use') self. resize(500, 500) self. widget_list() def widget_list(self): self. add_widget() def add_widget(self): cb = QComboBox(self) cb. resize(150, 30) cb. move(10, 50) btn = QPushButton('get data 1', self) btn. move(10, 100) btn2 = QPushButton('get data 2', self) btn2. move(120, 100) pass # add entry # *****************ADD ENTRY****************** START # cb.addItem('Hunan') # cb.addItem('Hubei') # cb.addItem(QIcon('../images/jpg/home.jpg'), 'Beijing') # cb.addItems(['Guangdong','Sichuan','Jiangxi','Guangxi']) # *****************ADD DATA******************END pass # insert entry # *****************INSERT ENTRY****************** START # cb.insertItem(0, 'Gansu') # cb.insertItem(1, QIcon('../images/jpg/save.jpg'), 'Shaanxi') # cb.insertItems(1, ('Heilongjiang','Jilin','Liaoning')) # *****************INSERT ENTRY******************END pass # set entry # *****************SET ENTRY****************** START # cb.setItemIcon(0, QIcon('../images/jpg/save.jpg')) # cb.setItemText(0,'Gansu Province') # cb.setItemData(0, 'Gansu') # *****************SET ENTRY******************END pass # model operation # *****************MODEL OPERATION****************** STARTING # Model operations, view operations, and proxy settings will be explained in detail later # *****************model operation****************** end pass # delete entry # *****************DELETE ENTRY****************** START # cb. removeItem(0) # ***************** DELETE ENTRY ******************* END pass # insert split line # *****************Insert Divider******************* START # cb. insertSeparator(3) # cb. insertSeparator(6) # *****************Insert Divider****************** End pass # set the default display value # *****************Set Default Display Value************************************************************************************* # cb. setCurrentIndex(4) # cb.setCurrentText('Guangdong') # cb. setEditable(True) # cb.setEditText('Guangdong Province') # *****************Set Default Display Value****************** End pass # get data # ***************Get Data****************** START # ls = ['Hunan','Guangdong', 'Sichuan', 'Jiangxi', 'Guangxi', 'Heilongjiang', 'Jilin', 'Liaoning','Hubei'] # for i, v in enumerate(ls): # cb. addItem(v, i * 10) # #def btn_cao(): # print('count:', cb. count()) # print('Index:', cb. currentIndex()) # print('Text:', cb. currentText()) # print('Date:', cb. currentData()) # print('Icon:', cb. itemIcon(cb. currentIndex())) # # def btn_cao2(): # print(cb. itemIcon(cb. count()-1)) # print(cb. itemText(cb. count()-1)) # print(cb. itemData(cb. count()-1)) # # # btn.clicked.connect(btn_cao) # # btn2.clicked.connect(btn_cao2) # print(cb. count()) # btn2.clicked.connect(lambda _, index=cb.count()-1: print(cb.itemIcon(index), cb.itemText(index), cb.itemData(index))) # # clicked(self, checked: bool = False) # # Since the clicked signal will emit a parameter False(0) by default, a "_" variable needs to be added to the lambda to ignore this parameter (or add a variable to receive this parameter, which will not be used later) # *****************Get Data****************** End pass # data entry limit # *****************Data Entry Limit****************** START # cb. setMaxCount(20) # cb. setMaxVisibleItems(15) # # ls = ['Hebei', 'Shanxi', 'Heilongjiang', 'Jilin', 'Liaoning', 'Jiangsu', 'Zhejiang', 'Anhui', 'Fujian', 'Jiangxi', 'Shandong', 'Henan ', 'Hubei', \ # 'Hunan', 'Guangdong', 'Hainan', 'Sichuan', 'Guizhou', 'Yunnan', 'Shaanxi', 'Gansu', 'Qinghai', 'Taiwan', 'Inner Mongolia', 'Guangxi', ' Tibet', \ # 'Ningxia', 'Xinjiang', 'Beijing', 'Tianjin', 'Shanghai', 'Chongqing', 'Hong Kong', 'Macau'] # for i, v in enumerate(ls): # cb. addItem(v, i * 10) # *****************Data Entry Limit****************** End pass # normal operation # *****************General Operation******************************************************************************************* # ls = ['Hebei', 'Shanxi', 'Heilongjiang', 'Jilin', 'Liaoning', 'Jiangsu', 'Zhejiang', 'Anhui', 'Fujian', 'Jiangxi', 'Shandong', 'Henan ', 'Hubei', \ # 'Hunan', 'Guangdong', 'Hainan', 'Sichuan', 'Guizhou', 'Yunnan', 'Shaanxi', 'Gansu', 'Qinghai', 'Taiwan', 'Inner Mongolia', 'Guangxi', ' Tibet', \ # 'Ningxia', 'Xinjiang', 'Beijing', 'Tianjin', 'Shanghai', 'Chongqing', 'Hong Kong', 'Macau'] # for i, v in enumerate(ls): # cb. addItem(v, i * 10) # # cb.setEditable(True) # Whether the selected entry is allowed to be edited # cb.setDuplicatesEnabled(False) # When an editable item is duplicated, whether it is allowed to be appended to the drop-down box # cb.setFrame(False) # Whether to display the frame # # cb.setItemIcon(0, QIcon('../images/jpg/home.jpg')) # Set item icon # # cb.setItemIcon(1, QIcon('../images/jpg/edit.jpg')) # Set item icon # # cb.setIconSize(QSize(100, 100)) # Uniformly set icon size # cb.setSizeAdjustPolicy(QComboBox.AdjustToContents) # Set the drop-down box size adjustment policy # cb.setMinimumContentsLength(10) # Set the minimum content length # *****************General Operation****************** End pass # other operations # *****************OTHER OPERATIONS****************** START # ls = ['Hebei', 'Shanxi', 'Heilongjiang', 'Jilin', 'Liaoning', 'Jiangsu', 'Zhejiang', 'Anhui', 'Fujian', 'Jiangxi', 'Shandong', 'Henan ', 'Hubei', \ # 'Hunan', 'Guangdong', 'Hainan', 'Sichuan', 'Guizhou', 'Yunnan', 'Shaanxi', 'Gansu', 'Qinghai', 'Taiwan', 'Inner Mongolia', 'Guangxi', ' Tibet', \ # 'Ningxia', 'Xinjiang', 'Beijing', 'Tianjin', 'Shanghai', 'Chongqing', 'Hong Kong', 'Macau'] # for i, v in enumerate(ls): # cb. addItem(v, i * 10) # # cb. setEditable(True) # btn.setText('Clear all entries') # btn2.setText('Clear edit entries') # btn.clicked.connect(lambda :cb.clear()) # Clear all entries # btn2.clicked.connect(lambda :cb.clearEditText()) # Clear the current edited entry # btn.setText('Pop up drop-down box') # btn.clicked.connect(lambda:cb.showPopup()) # cp = QCompleter(['Fengzi','Shixinfeng','aaa','bbb','ababa']) # cb.setCompleter(cp) # completer # vld = QValidator # cb. setValidator(vld) # *****************Other Operations****************** End pass # Available signals # ***************AVAILABLE SIGNALS**************** STARTING ls = ['Hebei', 'Shanxi', 'Heilongjiang', 'Jilin', 'Liaoning', 'Jiangsu', 'Zhejiang', 'Anhui', 'Fujian', 'Jiangxi', 'Shandong', 'Henan' , 'Hubei', \ 'Hunan', 'Guangdong', 'Hainan', 'Sichuan', 'Guizhou', 'Yunnan', 'Shaanxi', 'Gansu', 'Qinghai', 'Taiwan', 'Inner Mongolia', 'Guangxi', 'Tibet' ', \ 'Ningxia', 'Xinjiang', 'Beijing', 'Tianjin', 'Shanghai', 'Chongqing', 'Hong Kong', 'Macau'] for i, v in enumerate(ls): cb. addItem(v, i * 10) # cb.setEditable(True) # Whether the selected entry is allowed to be edited # cb.activated.connect(lambda val:print('The selected item has changed',val)) # cb.activated[str].connect(lambda val:print('The selected item has changed',val)) # # cb.currentIndexChanged.connect(lambda val: print('The currently selected index has changed',val)) # cb.currentIndexChanged[str].connect(lambda val: print('The currently selected index has changed',val)) # # cb.currentTextChanged.connect(lambda val: print('The selected text has changed', val)) # # cb.editTextChanged.connect(lambda val:print('The editable text has changed', val)) # # btn.clicked.connect(lambda :cb.setItemText(0, 'Test it')) btn2.clicked.connect(lambda:cb.setCurrentIndex(2)) # cb.highlighted.connect(lambda val:print('highlighted', val)) # cb.highlighted[str].connect(lambda val:print('highlighted', val)) cb.textHighlighted.connect((lambda val:print('texthighlighted', val))) # ***************AVAILABLE SIGNALS**************** END if __name__ == '__main__': app = QApplication(sys. argv) window = Windows() window. show() sys. exit(app. exec_())
- Example 2: The case of the second-level linkage drop-down box
- Requirements: Given city data, realize two-level linkage effect. Output the ID corresponding to the city after selecting the city
from PyQt5.Qt import * import sys class Windows(QWidget): def __init__(self): super().__init__() self.setWindowTitle('QComboBox-secondary linkage') self. resize(500, 500) self.pro_dic = {'Hunan': {'Changsha':'001001', 'Zhuzhou':'001002', 'Xiangtan':'001003', 'Hengyang':'001004', 'Shaoyang':'001005', 'Yueyang': '001006', 'Zhangjiajie': '001007', 'Yiyang': '001008', 'Changde': '001009', 'Loudi': '001010', 'Chenzhou': '001011', 'Yongzhou': '001012', 'Huaihua': '001013' }, 'Beijing':{'Dongcheng District':'002001', 'Xicheng District': '002002', 'Chaoyang District': '002003', 'Fengtai District': '002004', 'Shijingshan District':'002005', 'Haidian District': '002006', 'Shunyi District': '002007', 'Tongzhou District': '002008', 'Daxing District': '002009', 'Fangshan District': '002010', 'Mentougou District': '002011', 'Changping District': '002012', 'Pinggu District': '002013', 'Miyun District': '002014', 'Huairou District': '002015', 'Yanqing District':'002016'}, 'Guangdong':{'Guangzhou':'003001', 'Shenzhen':'003002', 'Zhuhai':'003003', 'Shantou':'003004', 'Foshan': '003005', 'Shaoguan':'003006', 'Zhanjiang':'003007', 'Zhaoqing':'003008', 'Jiangmen':'003009', 'Maoming': '003010', 'Huizhou':'003011', 'Meizhou': '003012', 'Shanwei':'003013', 'Heyuan': '003014', 'Yangjiang':'003015', 'Qingyuan':'003016', 'Dongguan':'003017', 'Zhongshan': '003018', 'Chaozhou': '003019', 'Jieyang':'003020'} } self. widget_list() def widget_list(self): self. add_widget() def add_widget(self): cb_province = QComboBox(self) cb_city = QComboBox(self) self.cb_province = cb_province self.cb_city = cb_city cb_province.resize(150, 30) cb_city.resize(150, 30) x = 10 y = 10 cb_province. move(x, y) cb_city.move(cb_province.x() + cb_province.width() + 5, cb_province.y()) # Trigger the signal when the province changes, and link the city drop-down box cb_province.currentIndexChanged[str].connect(self.pro_changed) # Trigger a signal when the city changes, and print the ID corresponding to the city self.cb_city.currentIndexChanged.connect(self.city_changed) # Add data to the province drop-down box control cb_province.addItems(self.pro_dic.keys()) def pro_changed(self, pro_name): self.cb_city.blockSignals(True) # Cancel the city drop-down box to send signals # Clear the city drop-down box entries self.cb_city.clear() self.cb_city.blockSignals(False) # Restore city drop-down box emission signal # The city drop-down box control adds the city and ID corresponding to the province for key, val in self.pro_dic[pro_name].items(): self.cb_city.addItem(key, val) def city_changed(self, city_index): # Get the city ID city_id = self.cb_city.itemData(city_index) print(city_id) if __name__ == '__main__': app = QApplication(sys. argv) window = Windows() window. show() sys. exit(app. exec_())
- Example 3: QFontComboBox Example
from PyQt5.Qt import * import sys class Windows(QWidget): def __init__(self): super().__init__() self.setWindowTitle('QFontComboBox-create and use') self. resize(500, 500) self. widget_list() def widget_list(self): self. add_widget() def add_widget(self): label = QLabel(self) label.setText("I love learning Python programming!") label. move(20, 50) fcb = QFontComboBox(self) fcb.setEditable(False) # Set the selected item cannot be edited fcb. move(20, 100) # ***************** Set Filter ******************* START fcb.setFontFilters(QFontComboBox.AllFonts) # Display all fonts # fcb.setFontFilters(QFontComboBox.ScalableFonts) # Display scalable fonts # fcb.setFontFilters(QFontComboBox.NonScalableFonts) # Display non-scalable fonts # fcb.setFontFilters(QFontComboBox.MonospacedFonts) # Display monospaced fonts # fcb.setFontFilters(QFontComboBox.ProportionalFonts) # Display proportional fonts # *****************Set Filter****************** End # ***************AVAILABLE SIGNALS**************** STARTING # A signal occurs when the current font changes, passing a QFont object fcb.currentFontChanged.connect(lambda font:labe.setFont(font)) # Emit a signal when the current index number changes, passing the entry index number fcb.currentIndexChanged.connect(lambda index:print('index has changed',index)) # (overload) emit a signal when the current index number changes, passing the entry display text fcb.currentIndexChanged[str].connect(lambda s:print('index has changed',s)) # ***************AVAILABLE SIGNALS**************** END if __name__ == '__main__': app = QApplication(sys. argv) window = Windows() window. show() sys.exit(app.exec_())
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledgePython entry skill treeDesktop application developmentPyQT291713 people are studying systematically