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);
----------------------------------------------------------------------------------------------------------------
Subscribe to:
Post Comments (Atom)
this is such a great code...
ReplyDeleteit rocks...
bran you are the man..
Thanks man.
ReplyDeleteTo enable again use:
QVariant v(1 | 32);
That is:
QVariant v(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
Regards
Thanks. This helped.
ReplyDeleteIt works!
ReplyDeleteThank you
You are a legend. THANK YOU!! :)
ReplyDeleteYou just saved my day... thanks!
ReplyDelete+1. Thanks.
ReplyDeleteIn case your combo box is using a QStandardItemModel (which it does by default) then you may stay away from the `Qt::UserRole -1` hack:
ReplyDeleteconst 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);