Input component QComboBox –combo box/drop-down list

The QComboBox class is a direct subclass of the QWidget class, which implements a combo box
1. Properties in the QComboBox class

Common properties

void setItemIcon(int index, const QIcon & amp;icon); // Set the icon of the item
void setIconSize(const QSize & amp;size); // Set the icon size of the item
//Set user data for item
void setItemData(int index, const QVariant & amp;value, int role = Qt::UserRole);
void setMaxCount(int max); // Set the maximum allowed number of items
QString itemText(int index) const; // Get the text of item
QIcon itemIcon(int index) const; // Get the icon of the item
QSize iconSize() const; // Get the icon size of the item
QVariant itemData(int index, int role = Qt::UserRole) const; // Get user data of item
int count() const; // Get the number of items
int maxCount() const; // Get the maximum allowed number of items
QComboBOx class (combo box) attribute cheat sheet
Attribute name Description Attribute name Description
count Get the number of items minimumContentsLength Minimum number of characters in combo box
maxCount Maximum number of items allowed maxVisibleItems The maximum number of items displayed to the user
editable Whether it can be edited sizeAdjustPolicy combination Box size change policy
currentIndex The index of the current item insertPolicy When inserting a new item in combo box
Position strategy
currentText The text of the current item duplicatesEnabled Whether the content can be repeated
iconSize The size of the icon in the combo box modelColumn The visible column in the model
frame Whether to draw the default border currentData The data of the current project

①, count: const int
Access function: int count() const;
Get the number of items in the combo box, by default for an empty combo box or a combo box with no current item set,
Its value is 0.
②, maxCount: int
Access function: int maxCount() const; void setMaxCount(int);
This property describes the maximum number of items allowed in the combo box. If the maximum number set is less than the current number of items in the combo box,
then additional items will be truncated. The default value is the highest signed integer available (usually 2147483647).
③、 maxVisibleItems: int
Access function: int maxVisibleItems() const; void setMaxVisibleItems(int);
This property describes the number of items the combo box displays to the user on the screen (i.e. number of visible items)

④. minimumContentsLength: int
Access function: int minimumContentsLength() const; void setMinimumContentsLength(int);

This attribute describes the minimum number of characters for the combo box item (see the figure below). If this attribute is a positive value, then
minimumSizeHint() and sizeHint() are taken into account and default to 0.


⑤, sizeAdjustPolicy: SizeAdjustPolicy
Access function: SizeAdjustPolicy sizeAdjustPolicy() const;

void setSizeAdjustPolicy(SizeAdjustPolicy);

? This property describes how the size of the combo box changes when its contents change. The default value is
AdjustToContentsOnFirstShow. Note that when editable is enabled, this property needs to be in editable
attribute, otherwise the attribute may not have any effect.
? SizeAdjustPolicy is an enumeration in the QComboBox class that describes the size change policy of the combo box,
Its members are as follows

QComboBox::SizeAdjustPolicy enumeration (no flag)
Members Values Description
QComboBox::AdjustToContents 0 Adjust according to content< /strong>(See the picture below)
QComboBox::AdjustToContentsOnFirstShow (default value) 1 When displayed for the first time , adjust according to the content
QComboBox::AdjustToMinimumContentsLength 2 Use AdjustToContents or
AdjustToContentsOnFirstShow instead
QComboBox::AdjustToMinimumContentsLengthWithIcon 3 Adjust to minimumContentsLength property
size plus space for the icon.

⑥, insertPolicy: InsertPolicy
Access function: InsertPolicy insertPolicy() const; void setInsertPolicy(InsertPolicy);
This property describes the position where it should appear in the combo box when inserting a new item. The default is InsertAtBottom(new item
Insert to bottom), where InsertPolicy is an enumeration in the QComboBox class that describes the inserted item
The destination location, its members are shown in the table below.

QComboBox::InsertPolicy enumeration (no flag)
Members Value Description
QComboBox::NoInsert 0 The string will not be inserted into the combo box
QComboBox::InsertAtTop 1 String insertion into the first item in the combo box
QComboBox::InsertAtCurrent 2 Replace the current item with a string
QComboBox::InsertAtBottom< /strong> 3 The string is inserted after the last item of the combo box (default value)
QComboBox:: InsertAfterCurrent 4 String inserted after the current item of the combo box
QComboBox::InsertBeforeCurrent 5 The string is inserted before the current item of the combo box
QComboBox::InsertAlphabetically 6 Strings are inserted into the combo box in alphabetical order.

⑦. editable: bool

Access function: bool isEditable() const; void setEditable(bool);
This property describes whether the combo box can be edited by the user. Defaults to fasle.
NOTE: When this property is disabled, validator and completer are removed.

⑧、 duplicatesEnabled: bool
Access function: bool duplicatesEnabled() const; void setDuplicatesEnabled(bool);
This property describes whether the user can enter repeated items into the combo box. Note: Programmatically this is always possible

Insert repeating items into a combo box. Defaults to false (no duplicates allowed)
⑨、 currentData: const QVariant //qt5.2
Access function: QVariant currentData(int role = Qt::UserRole) const;
Saves data for the current item. This property is used by default for an empty combo box or a combo box with no current item set.
Invalid QVariant.
⑩、 currentIndex: int
Access function: int currentIndex() const; void setCurrentIndex(int);
Signal: currentIndexChanged(int); void currentIndexChanged(const QString & amp;);
This property describes the combo box’s index of the current item (starting from 0). When inserting or deleting, the index may change.
In an empty combo box or a combo box with no current item set, the value of this property is -1 by default.
?, currentText: QString
Access function: QString currentText() const; void setCurrentText(const QString & amp;);
Signal: void currentTextChanged(const QString & amp;);
? This attribute describes the current text. Note: The setting function setCurrentText() cannot add new text to
In a combo box, this function can only make the combo box display the text.
? This property’s setTextCurrentText() will only work if the combo box is editable.
? If the combo box is editable, currentText is the text displayed when editing,
? If the combo box is empty or the current item’s combo box is not set, the value of the current item or an empty string.
? If the combo box is editable, the setCurrentText() function only needs to call the setEditText() function.
?, iconSize: QSize
Access function: QSize iconSize() const; void setIconSize(const QSize & amp;);
This property describes the size of the icon displayed in the combo box. The default value is the largest size the icon can have, smaller sizes
sized icons will not be enlarged.
?, frame: bool
Access function: bool hasFrame() const; void setFrame(bool);
This property describes whether the combo box draws a default border. The default is true (enabled)
?, modelColumn: int
Access function: int modelColumn() const; void setModelColumn(int);
This property describes the column visible in the model. If this property is set before the content that populates the combo box, the pop-up view
The graph is not affected and column 1 (default) is displayed. Default is 0

Properties of QComboBox (combo box) Example: (Create QT project + add core;gui;widgets)

//m.h file content
#ifndef M_H
#define M_H
#include<QtWidgets>
#include <iostream>
using namespace std;

class B:public QComboBox{
Q_OBJECT
public: B(QWidget* p=0):QComboBox(p){}
public slots:
    void f(){ cout<<currentIndex()<<endl; //Get the index of the current item
        cout<<currentText().toStdString()<<endl; //Get the text of the current item
    }
    void f1(){setCurrentText("EEE"); }//Display EEE in the combo box, but will not add it to the combo box
};
#endif // M_H


//Contents of the m.cpp file
#include "m.h"
int main(int argc, char *argv[]){
    QApplication a(argc,argv);
    QWidget w;
    QPushButton *b=new QPushButton("cout", & amp;w); b->move(22,22);
    QPushButton *b1=new QPushButton("currentText", & amp;w); b1->move(99,22);
    
    //Create combo box object
    B *pc1=new B( & amp;w); pc1->move(55,55);
    //Add content to the combo box
    pc1->insertItem(1,"AAA"); pc1->insertItem(2,"BBB"); pc1->insertItem(4,"CCC");
    QObject::connect(b, & amp;QPushButton::clicked, pc1, & amp;B::f); //Connect signals and slots
    QObject::connect(b1, & amp;QPushButton::clicked, pc1, & amp;B::f1);
    
    pc1->setSizeAdjustPolicy(QComboBox::AdjustToContents); //Automatically adjust the size of the combo box according to the content
    pc1->setCurrentIndex(1); //Set the index of the current item to 1, and the item with index 1 will be displayed during initial display.
    pc1->setDuplicatesEnabled(true); //Duplicate content can be added to the combo box.
    pc1->setEditable(1); //Make the combo box editable
    pc1->setInsertPolicy(QComboBox::InsertAtCurrent);//The inserted content replaces the current item
    w.resize(300,200); w.show();
    return a.exec();
}

2. Member functions in the QComboBox class

Commonly used functions

comboBox->addItem("cxq"); //Add drop-down option
combobox->clear(); //Clear the drop-down items
 
comboBox->setCurrentIndex(0);//Set the current index
int currentlndex(): //Returns the serial number of the current item. The serial number of the first item is 0.
combobox->currentText(); //Get the content of the current item
QVariant currentData(int role = Qt::UserRole): Returns the associated data of "current item"
QVariant itemData(int index, int role = Qt%:UserRole) Returns the associated data of "the item with the specified index number".
 
comboBox->itemText(2); //Get the content of the second item
combobox->count(); //Get the number of items
 
void removeItem(int index); //Delete item by specifying index

①、 QComboBox(QWidget* parent = Q_NULLPTR); //Constructor
②. void addItem(const QString & amp; text, const QVariant & amp; userData = QVariant());
void addItem(const QIcon & amp;icon , const QString & amp;text, const QVariant & amp; userData = QVariant());
void addItems(const QStringList & amp;texts); //Note the letter s after this function
The above function is used to add content to the combo box, where userData (you do not need to understand this parameter for the time being) is stored in
in Qt::UserRole.
③. void setItemText(int index, const QString & amp;text);
QString itemText(int index) const;
The above functions respectively represent setting the item at index index to text (can be used to modify the item), and getting
The index is the text at index . Indexes start from 0.
④. void setItemIcon(int index, const QIcon & amp;icon);
QIcon itemIcon(int index) const;
The above functions respectively represent setting the icon of the item at index index to icon and getting the index as index
icon. Indexes start from 0.
⑤. void insertItem(int index, const QString & amp;text, const QVariant & amp;userData = QVariant());
void insertItem(int index, const QIcon &icon, const QString &text,
const QVariant & amp;userData = QVariant());
void insertItems(int index, const QStringList & amp;list); //Note the last letter s
The above function is used to insert content into the combo box. If the specified index is greater than or equal to the total number of items, the new item is
Appends to the end of the item. If the index is 0 or negative, the new item is added in front of the existing item.
⑥. void removeItem(int index);
Delete the item at the specified index. If the index is deleted, the current index will be updated. If the index is out of range, this function will
The number does nothing.
⑦. void clear() //Slot, clearall items in the combo box
⑧、void insertSeparator(int index);
Insert a separator at index index. If the specified index is greater than or equal to the total number of items, the new item is appended.
To the end of the item, if the index is 0 or negative, the new item is added in front of the existing item. Note: insert
The dividers may not be visually obvious.
⑨、 void setLineEdit(QLineEdit* edit);
Set the text editing component of the combo box to edit. After setting this item, the combo box will become editable.
⑩、 QLineEdit* lineEidt() const;
Returns the Line Editor in the combo box, or 0 if there is none. Only editable combo boxes will have row editors.
?, void setEditText(const QString & amp;text); //Slot
Set the text of the combo box to text. This function cannot add new text to the combo box. It can only make the combo box
Display this text. This function only works when the combo box is editable. This function is the same as currentText
The attribute setting function is similar to setCurrentText().
void clearEditText() //slot
This function is used to clear the text set by the setEditText() function, and can also be used to clear the text being edited.

?, virtual void showPopup(); //virtual function
virtual void hidePopup() //virtual function
The above functions are used to show or hide a list of items.
?, int findText(const QString & amp;text , Qt::MatchFlags flags = static_cast
(Qt::MatchExactly | Qt::MatchCaseSensitive)) const;
Find the index of the item where text is located. The Qt::MatchFlag enumeration is used to describe the matching method when searching.

Qt::MatchFlags is the flag of this enumeration. The default allocation method here is to perform matching based on QVariant.
And the search is case-sensitive. Please refer to the “Component Public Enumeration” chapter for details.
?,
const QValidator* validator() const; void setValidator( const QValidator* validator);
The above functions are used to set and obtain QValidator (validator). The validator is used to verify the input text.
That is to say, you can use this class to limit the user’s input (for example, only numbers can be entered, etc.). The QValidator class will be in
Explained later. The validator requires the combo box to be editable.

Add, set, insert, remove, clear, and find the content of QComboBox (combo box) Example:

//1. Contents of m.h file
#ifndef M_H
#define M_H
#include<QtWidgets>
#include <iostream>
using namespace std;

//Note: Organizing the program in the following way can facilitate the association of signals and slots
class B :public QWidget {
Q_OBJECT
public: //Create components
QPushButton *b; QPushButton *b1; QPushButton *b2; QPushButton *b3;
QPushButton *b4; QPushButton *b5; QPushButton *b6; QComboBox *pc1; QLineEdit *pe;
\t
B(QWidget* p = 0) :QWidget(p) { //Constructor starts
//Create and layout widgets
b = new QPushButton("add", this); b1 = new QPushButton("set", this);
b2 = new QPushButton("insert", this); b3 = new QPushButton("remove", this);
b4 = new QPushButton("clear", this); b5 = new QPushButton("show", this);
b6 = new QPushButton("find", this);
b->move(22, 22); b1->move(22, 44); b2->move(22, 66); b3->move(22, 88);
b4->move(22, 111); b5->move(22, 133); b6->move(22, 155);
pc1 = new QComboBox(this); pc1->move(111, 77);
pe = new QLineEdit("XXXX", this); pe->move(111, 44);
pc1->setSizeAdjustPolicy(QComboBox::AdjustToContents); //The combo box automatically adjusts its size according to the content
//Add text to combo box pc1
QStringList s;
s.append("AAA"); s.append("BBB"); s.append("CCC"); s.append("DDD");
pc1->addItems(s);
//Connect signals and slots
QObject::connect(b, & amp;QPushButton::clicked, this, & amp;B::addf);
QObject::connect(b1, & amp;QPushButton::clicked, this, & amp;B::setf);
QObject::connect(b2, & amp;QPushButton::clicked, this, & amp;B::insertf);
QObject::connect(b3, & amp;QPushButton::clicked, this, & amp;B::removef);
QObject::connect(b4, & amp;QPushButton::clicked, pc1, & amp;QComboBox::clear);
QObject::connect(b5, & amp;QPushButton::clicked, this, & amp;B::showf);
QObject::connect(b6, & amp;QPushButton::clicked, this, & amp;B::findf);
} //Constructor ends
\t
public slots:
void addf() { QString s = pe->text(); pc1->addItem(s); } //Add text s at the end
void setf() {
QString s = pe->text();
int i = pc1->currentIndex();
pc1->setItemText(i, s);
}//Set the text at the current index number to s
\t
void insertf() {
QString s = pe->text();
int i = pc1->currentIndex();
pc1->insertItem(i, s);
}//Insert text s at the current index number
\t
void removef() { int i = pc1->currentIndex(); pc1->removeItem(i); }//Remove the text at the current index number
void showf() { pc1->showPopup(); }
void findf() {
QString s = pe->text();
//Perform fuzzy search and case sensitive
cout << pc1->findText(s, Qt::MatchContains | Qt::MatchCaseSensitive) << endl;
}
};
#endif // M_H


//2. Contents of m.cpp file
#include "Header.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
B mb; mb.resize(300, 200); mb.show();
\t
return a.exec();
}

3. Signal in the QComboBox class

Common signals

void currentindexChanged(int index);//Emit this signal when the selection changes

void currentindexChanged(const QString & amp;text);//Emit this signal when the selection changes

①. void activated(int index); void activated(const QString & amp;text); //Signal

? When the user selects an item in the combo box, the above signal is sent, where index is the selected item
Index, text is the text of the selected item.
? NOTE: The above signal is sent even if the selection has not changed (i.e. the same item is selected twice).
? Note: Merely moving the highlight bar in an expanded drop-down list in a group will not cause the item to be selected.
You will need to click the mouse or press the enter key to select the item. You can also click the next button when the combo box gets focus.
While the drop-down list is hidden, use the up/down arrow keys on your keyboard to select an item in the combo box.

②. void currentIndexChanged(int index); //Sent when the currentIndex property changes
void currentIndexChanged(const QString & amp;text); //Sent when the currentIndex property changes
void currentTextChanged(const QString & amp;text); //Sent when the currentText property changes

? When the currentIndex or currentText property of the combo box is changed by the user or programmatically,
The above signal will be sent. where index is the index of the changed item, text is the changed item
text.
? Note: The condition for sending the above signal is that the currentIndex or currentText property changes. The following is the change.
time to change
? These two properties will change after selecting different items, that is to say, when the combo box is expanded
Merely moving the highlight bar in the pick list will not change these two properties. The item needs to be selected (using
When the mouse clicks or the enter key is pressed) and the same item as before cannot be selected, currentIndex or
The currentText property will change.
? When the combo box is in the editable state and the content of the text is changed in the combo box, the currentText property
The property will change, but the currentIndex property will not.
④. void editTextChanged(const QString & amp;text); //Signal
This signal is sent when the text is changed in the Line Editor component of the combo box. text is the new text after the change.
The timing of the text change is the same as the timing of the currentText property change. See the currentTextChanged signal for details.

⑤. void highlighted(int index); //Signal
void highlighted(const QString & amp;text); //Signal

The above signal is sent when the highlight bar is changed in the expanded drop-down list of the combo box.
⑥. To test the above signal sending timing, readers can write their own programs to verify.

4. Set the style of the QComboBox drop-down box, which can be a list, tree, table, etc.

void setView(QAbstractItemView *itemView)
model/view use

QComboBox uses the model/view framework for its popup list and to store its items. By default, QStandardItemModel stores items and QListView subclasses display popup lists. I will reorganize this later by connecting Model/View with this.