【问题标题】:Get the Contents of a QComboBox获取 QComboBox 的内容
【发布时间】:2014-11-12 18:47:46
【问题描述】:

我需要在QComboBox 中获取一个QStringList 或包含所有QStrings 的数组。

我找不到执行此操作的QComboBox 方法,实际上我什至找不到执行此操作的QAbstractItemModel 方法。

真的是我唯一的选择吗:

std::vector< QString > list( myQComboBox.count() );

for( auto i = 0; i < list.size(); i++ )
{
    list[i] = myQComboBox.itemText( i );
}

【问题讨论】:

  • 没有这样的功能,AFAK。你为什么不喜欢你使用的方法(迭代组合框中的所有项目)?
  • @vahancho 我认为这很浪费,尤其是随着QComboBox 的大小增长。
  • 但是也许将组合框的内容存储到另一个容器中也很浪费?你为什么需要那个?这可以解释为什么API中没有这样的功能。
  • 值的容器为您提供了成员函数QComboBox::itemText 无法获得的什么?
  • 我要清除 myQComboBox 并重新填充它,我需要识别已更改的元素。

标签: c++ arrays qt qstring qcombobox


【解决方案1】:

您的答案看起来不错,但您也可以使用 QStringList 代替向量。

QStringList itemsInComboBox; 
for (int index = 0; index < ui->combo_box->count(); index++)
    itemsInComboBox << ui->combo_box->itemText(index);

【讨论】:

    【解决方案2】:

    QAbstractItemModel 可以包含图像、树木和其他可以保存在QVariant 中的数据。这就是为什么您无法从中获得QStringList 的原因。这是没有意义的。

    但是,有一个类QStringListModel 继承自QAbstractItemModel,旨在保留字符串。正如你所料,它有方法stringList()

    QComboBox 允许您将它使用的默认模型更改为另一个模型。默认情况下,它使用QStandardItemModel。创建组合框后将其更改为字符串列表模型。

     QStringListModel* cbModel = new QStringListModel();
     comboBox->setModel(cbModel);
    

    现在你可以得到你想要的:

    QStringList list = cbModel->stringList();
    

    【讨论】:

    • 这不是我希望的解决方案,但它确实解决了问题。
    【解决方案3】:

    不要进行过早的优化。你的代码没问题。您可以使用qobject_cast&lt;QStandardItemModel*&gt;(combo.model()); 来获得对组合框数据的扩展访问权限。

    此外,您可以实现自己的 QAbstractItemModel,它将数据存储为 QStringList,并提供对它的访问。

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 2019-12-15
      • 2012-01-07
      • 2021-10-04
      • 2010-12-12
      • 2019-08-25
      • 2016-10-26
      • 2013-09-15
      相关资源
      最近更新 更多