Qt: c++:如何使用QStringList填充QComboBox

Qt: c++: how to fill QComboBox using QStringList

本文关键字:填充 QComboBox QStringList c++ Qt 何使用      更新时间:2023-10-16

我正在尝试使用insertItems函数向QComboBox添加项目,如下所示:

QStringList sequence_len = (QStringList()
<< QApplication::translate("MainWindow", "1", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("MainWindow", "2", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("MainWindow", "3", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("MainWindow", "4", 0, QApplication::UnicodeUTF8)
<< QApplication::translate("MainWindow", "5", 0, QApplication::UnicodeUTF8)
);
ui->QComboBox->insertItem(0, &sequence_len);

但不工作,给我以下错误信息:

error: no matching function for call to 'QComboBox::insertItem(int, QStringList*)'

实际上,当我在课堂上写ui->QComboBox->insertItem(来查看Qt-Creator的建议时,选项:(int index, const QStringList & list)似乎不存在。所以,一开始,我认为这是因为我的Qt-Creator不支持这个功能。然而,令人惊讶的是,当创建QComboBox小部件后,直接从Qt-Creator中的"设计"选项卡填充QComboBox时,ui_mainwindow.h正在使用相同的功能。

为什么会发生这种情况,是否有一种方法可以将此函数添加到我的类?

使用QComboBox的addItems或insertItems成员函数。//注意,对于接受QStringList参数的函数,最后有一个s:它是add/insert Items

LE:不要传递QStringList的地址,函数接受对QStringList对象的引用,而不是指针,使用:ui->QComboBox->insertItems(0, sequence_len); //no & before sequence_len

填写QComboBox的完整示例(考虑到tr()已正确设置):

QStringList sequence_len = QStringList() << tr("1") << tr("2") << tr("3") << tr("4") << tr("5");
//add items:
ui->QComboBox->addItems(sequence_len);
//insert items into the position you need
//ui->QComboBox->insertItems(0, sequence_len);

不要将字符串列表作为指针传递

ui->QComboBox->insertItem(0, sequence_len);

试试这个:

//Text that you want to QStringList
QStringList list;
list << "a" << "b" << "c";
//Instance of model type to QStringList
QStringListModel *model = new QStringListModel();
model->setStringList(list);
ui->QComboBox->setModel(model);

在这种情况下,QStringList list可以是sequence_len中的列表。