barcaroller
barcaroller

Reputation: 131

How to modify window contents based on QComboBox value

I have a Qt window which contains a QComboBox and a few QLabels and QLineEdits. Based on the QComboBox value that the user chooses, I would like to dynamically change the QLabels and QLineEdits in the window while it is still open.

For example, if the QComboBox has a list of countries, and the user chooses France, I would like to change all the QLabels and QLineEdits into French; the user is then expected to fill out the QLineEdits in French before clicking on the Save/Close button at the bottom.

Can this be done in Qt?

Upvotes: 0

Views: 285

Answers (1)

DaveK
DaveK

Reputation: 715

If you are only looking for language translating, there are other ways to do that in Qt where you can use dictionaries to translate Ui text. Take a look at https://doc.qt.io/qt-5/qtlinguist-hellotr-example.html

But it sounds like your question is not meant to be only about language, so to do this you can use the QComboBox signal currentTextChanged, and a slot that will receive the current value and update labels based on that text. Alternately if you do not want to use a bunch of ifs you could use the signal currentIndexChanged and use a switch.

In my ui file I have (4) objects: a comboBox and label1 through 3.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->comboBox->addItem("Selected Option 1");
    ui->comboBox->addItem("Selected Option 2");
    ui->comboBox->addItem("Selected Option 3");


    connect(ui->comboBox, &QComboBox::currentTextChanged,
            this,   &MainWindow::setLabelText);

}

void MainWindow::setLabelText(const QString comboText)
{
    if(comboText == "Selected Option 1")
    {
        ui->label1->setText("Text when option 1 is selected");
        ui->label2->setText("Text when option 1 is selected");
        ui->label3->setText("Text when option 1 is selected");
    }
    else if(comboText == "Selected Option 2")
    {
        ui->label1->setText("Text when option 2 is selected");
        ui->label2->setText("Text when option 2 is selected");
        ui->label3->setText("Text when option 2 is selected");
    }
    else if(comboText == "Selected Option 3")
    {
        ui->label1->setText("Text when option 3 is selected");
        ui->label2->setText("Text when option 3 is selected");
        ui->label3->setText("Text when option 3 is selected");
    }
}

In your header make sure you define setLabeText as a slot.

private slots:
    void setLabelText(const QString comboText);

Upvotes: 1

Related Questions