Disable Item in Qt Combobox

后端 未结 4 1691
孤街浪徒
孤街浪徒 2021-01-03 21:20

I can\'t find a standard way to disable an individual item in a Qt combo box. Is there a facility to do this in Qt that I am missing?

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 21:52

    In case your combo box is using a QStandardItemModel (which it does by default) then you may stay away from the Qt::UserRole -1 hack (see blog post to which Desmond refers to in his answer above):

    const QStandardItemModel* model = qobject_cast(ui->comboBox->model());
    QStandardItem* item = model->item(1);
    
    item->setFlags(disable ? item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled)
                           : Qt::ItemIsSelectable|Qt::ItemIsEnabled));
    // visually disable by greying out - works only if combobox has been painted already and palette returns the wanted color
    item->setData(disable ? ui->comboBox->palette().color(QPalette::Disabled, QPalette::Text)
                          : QVariant(), // clear item data in order to use default color
                  Qt::TextColorRole);
    

    Above code is a revised and more generic solution to my comment to the blog post.

提交回复
热议问题