Tuesday, January 25, 2011

Disabling QCombobox items

So I ran into the problem in Qt a while back of not being able to disable certain items in a QComboBox widget. Since when I was looking for it I couldn't find a solution, I figured I'd post the solution here even though nobody will probably ever read it.

You have to use the QAbstractItemModel's setFlags() method. Wait, what do you mean there's no setFlags() method? Oh, well just use the setData() method and have the role as 'Qt::UserRole - 1'. Because that makes so much sense. bleh. I hope qt fixes that.

Unfortunately I can't take a screenshot of it right now. But here's my solution anyways. Hope this helps somebody.


----------------------------------------------------------------------------------------------------------------
// Get the index of the value to disable
QModelIndex index = ui.comboBox->model()->index(1,0);

// This is the effective 'disable' flag
QVariant v(0);
//the magic

ui.comboBox->model()->setData( index, v, Qt::UserRole -1);
----------------------------------------------------------------------------------------------------------------

8 comments:

  1. this is such a great code...
    it rocks...


    bran you are the man..

    ReplyDelete
  2. Thanks man.

    To enable again use:

    QVariant v(1 | 32);

    That is:

    QVariant v(Qt::ItemIsSelectable | Qt::ItemIsEnabled);

    Regards

    ReplyDelete
  3. You are a legend. THANK YOU!! :)

    ReplyDelete
  4. You just saved my day... thanks!

    ReplyDelete
  5. 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:

    const QStandardItemModel* model = qobject_cast(ui->comboBox->model());
    QStandardItem* item = model->item(1);
    item->setFlags(disable ? Qt::NoItemFlags : Qt::ItemIsSelectable|Qt::ItemIsEnabled);
    // visually disable by greying out - works only if combobox has been painted and palette returns the wanted color
    item->setData(ui->comboBox->palette().color(disable ? QPalette::Inactive : QPalette::Normal, QPalette::Text),
    Qt::TextColorRole);

    ReplyDelete