QComboBox of Qt Programming: Common Functions and Sample Code
Introduction
The QComboBox widget, which provides a drop-down list of items for users to choose from.
Creating a QComboBox
To create a QComboBox, you can use the following code:
QComboBox *comboBox = new QComboBox(parent);
comboBox->addItem("Item 1");
comboBox->addItem("Item 2");
comboBox->addItem("Item 3");
This code creates a new QComboBox object and adds three items to it. The parent
argument specifies the parent widget of the QComboBox, which is typically the main window or a container widget.
Retrieving the Selected Item
To retrieve the currently selected item in a QComboBox, you can use the currentText()
function. Here’s an example:
QString selectedItem = comboBox->currentText();
The currentText()
function returns the text of the currently selected item as a QString. You can then use this value in your application as needed.
Handling Selection Changes
If you want to perform some action whenever the user selects a different item in the QComboBox, you can connect the activated()
signal to a slot. Here’s an example:
connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(handleSelectionChange(const QString&)));
In this code, the activated()
signal is emitted whenever the user selects a different item. It is connected to the handleSelectionChange()
slot, which is a custom function you can define to handle the selection change event. The selected item is passed as a parameter to the slot function.
Conclusion
The QComboBox widget is a versatile tool in Qt programming, allowing users to select items from a drop-down list.