Disable specific items in QComboBox

后端 未结 2 1801
轻奢々
轻奢々 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条回答
  •  Happy的楠姐
    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 
    
    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(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();
    }
    

提交回复
热议问题