How do i make dependent combo box in qt creator with C++ code. Lets say i have two combo box. I select option 1 in combo box 1, it should display certain option in combo box 2 only.
#include "mapproject.h"
#include "ui_mapproject.h"
#include <QFile>
#include <QString>
#include <QTextStream>
#include <QComboBox>
#include <QList>
MapProject::MapProject(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MapProject)
{
ui->setupUi(this);
QFile datafile("/home/spyros/untitled/data.csv");
if(datafile.open (QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream line(&datafile);
while (!line.atEnd()){
QString linetext=line.readLine();
const QStringList fields = linetext.split(',');
ui->comboBox->addItem(fields.first(), QVariant(fields.last()));
}
}connect(ui->comboBox, &QComboBox::currentTextChanged, [this](){
ui->label->setText(ui->comboBox->currentData().toString());
});
ui->comboBox_2->setEnabled(false);
ui->comboBox->setCurrentIndex(-1);
}
MapProject::~MapProject()
{
delete ui;
}
void MapProject::on_comboBox_currentIndexChanged(const QString &arg1)
{
ui->comboBox_2->setEnabled(true);
QString City = ui->label->text();
QFile cityfile("/home/spyros/untitled/"+City+".csv");
if(cityfile.open (QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream line(&cityfile);
while (!line.atEnd()){
QString linetext=line.readLine();
const QStringList fields = linetext.split(',');
ui->comboBox_2->addItem(fields.first(), QVariant(fields.last()));
}
}
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Add items to Combo Box
ui->combobox_options->addItem("Option 1");
ui->combobox_options->addItem("Option 2");
ui->combobox_options->addItem("Option 3");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btn_show_options_clicked()
{
QString str;
str.sprintf("%d", ui->combobox_options->currentIndex());
ui->lbl_sel_num->setText(str);
ui->lbl_sel_text->setText(ui->combobox_options->currentText());
}
Comments
Leave a comment