Disable specific items in QComboBox

后端 未结 2 1737
轻奢々
轻奢々 2020-12-16 17:09

In my application, I want to disable some items (i.e. not selectable, no highlights when mouse hovering above, and the texts are greyed out) in the QComboBox when certain co

相关标签:
2条回答
  • 2020-12-16 17:22

    The answer linked in my comment above seems to be talking about an old version of Qt. I have tested on Qt5.4 and Qt5.6 and there is no need set the color yourself here, you just need to set and/or clear the Qt::ItemIsEnabled flag, here is an example:

    #include <QtWidgets>
    
    int main(int argc, char *argv[]) {
      QApplication a(argc, argv);
      QComboBox comboBox;
      comboBox.addItem(QObject::tr("item1"));
      comboBox.addItem(QObject::tr("item2"));
      comboBox.addItem(QObject::tr("item3"));
      QStandardItemModel *model =
          qobject_cast<QStandardItemModel *>(comboBox.model());
      Q_ASSERT(model != nullptr);
      bool disabled = true;
      QStandardItem *item = model->item(2);
      item->setFlags(disabled ? item->flags() & ~Qt::ItemIsEnabled
                              : item->flags() | Qt::ItemIsEnabled);
      comboBox.show();
      return a.exec();
    }
    
    0 讨论(0)
  • 2020-12-16 17:42

    Here is the technique @Mike describes, wrapped up in a convenient utility function:

    void SetComboBoxItemEnabled(QComboBox * comboBox, int index, bool enabled)
    {
        auto * model = qobject_cast<QStandardItemModel*>(comboBox->model());
        assert(model);
        if(!model) return;
    
        auto * item = model->item(index);
        assert(item);
        if(!item) return;
        item->setEnabled(enabled);
    }
    
    0 讨论(0)
提交回复
热议问题