我有一个Qt窗口,其中包含一个QComboBox和一些QLabel和QLineEdits。根据用户选择的QComboBox值,我想在窗口仍处于打开状态时动态更改窗口中的QLabel和QLineEdits。
例如,如果QComboBox有一个国家列表,并且用户选择了France,我想将所有QLabel和QLineEdits更改为法语;然后,用户需要在单击底部的“保存/关闭”按钮之前用法语填写QLineEdits。
可以在Qt中完成吗?
如果您只是在寻找语言翻译,那么在Qt中还有其他方法可以使用词典翻译Ui文本。看看https://doc.qt.io/qt-5/qtlinguist-hellotr-example.html
但听起来你的问题不仅仅是关于语言,所以要做到这一点,你可以使用QComboBox信号currentTextChanged,以及一个接收当前值并根据该文本更新标签的插槽。或者,如果您不想使用一堆ifs,则可以使用信号currentIndexChanged并使用开关。
在我的ui文件中,我有(4)个对象:一个comboBox和label1到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");
}
}
在标题中,确保将setLabeText定义为插槽。
private slots:
void setLabelText(const QString comboText);