In this Qt5 GUI Development article iam going to show you to Create ComboBox Before starting our main topic , check Qt5 C++ GUI Development Articles with videos training and source codes.
Qt5 Tutorial : What is ComboBox
A QComboBox provides a means of presenting a list of options to the user in a way that takes up the minimum amount of screen space. A combobox is a selection widget that displays the current item, and can pop up a list of selectable items. A combobox may be editable, allowing the user to modify each item in the list.
How to Create ComboBox in Qt5?
So first of all you need to create a New Project in Qt5 C++ framework. After that open your dialog.ui and we are going to give a simple design. basically we need to add a combobox in our design. There are two ways that you can add items to combobox, the first way is by design. you need to right click on combobox and after that choose Edit Items, in the dialog you can add your items like this.
OK now the second way is by coding in C++ language, open your dialog.cpp and in the constructor add these line of codes .
1 2 3 4 |
ui->comboBox->addItem("Apple"); ui->comboBox->addItem("Banana"); ui->comboBox->addItem("Pear"); ui->comboBox->addItem("Melon"); |
And dialog.cpp will look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); ui->comboBox->addItem("Apple"); ui->comboBox->addItem("Banana"); ui->comboBox->addItem("Pear"); ui->comboBox->addItem("Melon"); } Dialog::~Dialog() { delete ui; } |
After ruining the project the result will be the same
Now it is time to implement a simple signal and slot mechanism to our project, for this you need to add a QPushButton with a QLabel in your design and remove the text of label. so after that right click on the QPushButton and select Go To Slot and clicked().
Add this line of code
1 |
ui->label->setText(ui->comboBox->currentText()); |
After adding dialog.cpp will look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); ui->comboBox->addItem("Apple"); ui->comboBox->addItem("Banana"); ui->comboBox->addItem("Pear"); ui->comboBox->addItem("Melon"); } Dialog::~Dialog() { delete ui; } void Dialog::on_pushButton_clicked() { ui->label->setText(ui->comboBox->currentText()); } |
Run the complete project and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email