【问题标题】:QComboBox - set selected item based on the item's dataQComboBox - 根据项目的数据设置选定的项目
【发布时间】:2011-05-19 10:22:04
【问题描述】:

从基于 enum 的唯一值的预定义列表中选择 QT 组合框中的项目的最佳方法是什么。

过去我已经习惯了 .NET 的选择风格,可以通过将 selected 属性设置为您希望选择的项目的值来选择项目:

cboExample.SelectedValue = 2;

如果数据是 C++ 枚举,是否有基于项目数据的 QT 执行此操作?

【问题讨论】:

    标签: c++ qt user-interface combobox qcombobox


    【解决方案1】:

    您使用findData() 查找数据的值,然后使用setCurrentIndex()

    QComboBox* combo = new QComboBox;
    combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
    combo->addItem .....
    
    float value=100.0;
    int index = combo->findData(value);
    if ( index != -1 ) { // -1 for not found
       combo->setCurrentIndex(index);
    }
    

    【讨论】:

      【解决方案2】:

      您还可以查看 QComboBox 中的 findText(const QString & text) 方法;它返回包含给定文本的元素的索引(如果未找到,则返回-1)。 使用这种方式的好处是添加item的时候不需要设置第二个参数。

      这是一个小例子:

      /* Create the comboBox */
      QComboBox   *_comboBox = new QComboBox;
      
      /* Create the ComboBox elements list (here we use QString) */
      QList<QString> stringsList;
      stringsList.append("Text1");
      stringsList.append("Text3");
      stringsList.append("Text4");
      stringsList.append("Text2");
      stringsList.append("Text5");
      
      /* Populate the comboBox */
      _comboBox->addItems(stringsList);
      
      /* Create the label */
      QLabel *label = new QLabel;
      
      /* Search for "Text2" text */
      int index = _comboBox->findText("Text2");
      if( index == -1 )
          label->setText("Text2 not found !");
      else
          label->setText(QString("Text2's index is ")
                         .append(QString::number(_comboBox->findText("Text2"))));
      
      /* setup layout */
      QVBoxLayout *layout = new QVBoxLayout(this);
      layout->addWidget(_comboBox);
      layout->addWidget(label);
      

      【讨论】:

      • 使用 findText() 从来都不好。 findData() 应该是首选方式。
      • 你的说法自相矛盾。我同意 findData 应该是“首选”方式,但不是唯一方式。我正在为现有系统编写逻辑,该系统有时会创建具有空数据值的“简单”组合框内容。所以通常 findData 就足够了,但有时在没有“数据”可查找的情况下需要 findText。
      【解决方案3】:

      如果您知道要选择的组合框中的文本,只需使用 setCurrentText() 方法来选择该项目。

      ui->comboBox->setCurrentText("choice 2");
      

      来自 Qt 5.7 文档

      设置器 setCurrentText() 只需调用 setEditText() 如果组合 框是可编辑的。否则,如果列表中有匹配的文本, currentIndex 设置为对应的索引。

      所以只要组合框不可编辑,函数调用中指定的文本就会在组合框中被选中。

      参考:http://doc.qt.io/qt-5/qcombobox.html#currentText-prop

      【讨论】:

      • ui->comboBox->setCurrentText("option") 是有效且简单的方法!
      • 也许值得注意的是,这在 Qt 4.x 中不可用,至少在 4.8 中不可用
      猜你喜欢
      • 2014-05-25
      • 2013-10-26
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2012-02-22
      相关资源
      最近更新 更多