【问题标题】:Qt: c++: how to fill QComboBox using QStringListQt: c++: 如何使用 QStringList 填充 QComboBox
【发布时间】:2013-06-07 06:48:57
【问题描述】:

我正在尝试使用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-&gt;QComboBox-&gt;insertItem( 以查看Qt-Creator 的建议时,选项:(int index, const QStringList &amp; list) 似乎不存在。所以,一开始我以为是因为我的Qt-Creator不支持这个功能。然而,令人惊讶的是,在创建 QComboBox 小部件后直接从 Qt-Creator 的“设计”选项卡中填充 QComboBox 时,ui_mainwindow.h 正在使用相同的功能。

为什么会发生这种情况,有没有办法将此功能也添加到我的班级?

【问题讨论】:

    标签: c++ qt qt5 qcombobox


    【解决方案1】:

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

    LE:不要传递你的 QStringList 的地址,该函数引用一个 QStringList 对象,而不是指针,使用:ui-&gt;QComboBox-&gt;insertItems(0, sequence_len); //no &amp; 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);
    

    【讨论】:

    • 谢谢。删除指针并用 addItem 替换 insertItem 使其工作。
    • insertItems 也应该可以工作,正是我的匆忙阅读让我指向 addItems - 然后我看到了你遇到的错误...... LE: 再次出错 - 它也有 insertItem_s_ (应该可以工作)
    • 您在问题描述中正确地说 insertItems,但在代码中您使用 insertItem(末尾没有 s)请参阅此处的文档:qt-project.org/doc/qt-4.8/qcombobox.html#insertItems
    • 谢谢 .. 我根本没有注意到缺少的“s”。这就是它不起作用的原因。
    • @Zlatomir 我有意格式化代码而不创建其他变量来显示如何“在一行代码中”填充 QComboBox。当然,关于代码格式的最终​​决定取决于您。
    【解决方案2】:

    试试这个:

    //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 中的列表。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多