How to disable few lines in the QComboBox or change their color?
-
Could you please advise how to change color of few lines in the QComboBox or how to disable them? I mean that all lines in the ComboBox have normal color and are enabled, but only few lines are disabled or at least have another color.
-
Hi and welcome to devnet,
You can do something like this:
@
// e.g. constructor
QStandardItemModel *model = new QStandardItemModel(5, 1);
for (int i = 0 ; i < 5 ; ++i {
model->setItem(i, new QStandardItem(tr("Test %1").arg(i));
}
comboBox->setModel(model);// Disable elements
QStandardItemModel* model = qobject_cast<QStandardItemModel*>(comboBox->model());for (int i = 0 ; i < comboBox->count() ; ++i) {
QStandardItem *item = model->item(i);
item->setEnabled(yourEnableCondition);
}
@Hope it helps
EDIT: Added missing model initialization following André's comment
-
I would not rely on QComboBox using a QStandardItemModel internally. Sure, that may be the case now, but if that's the case, it is a private implementation detail. Instead, I'd simply use my own model (which might be a QStandardItemModel, or perhaps a model that is build directly on top of my data store) on the QComboBox.
-
Indeed, you're right, I forgot to specify that I've set a QStandardItemModel on the combo box in my example.
-
SGaist, thank you very much for your help! :)
The StandardItemModel is absolutely what I need and schema “model <–> view ” is very interesting in general.
StandardItemModel has only one weakness against usual qcombobox using. It’s the searching of item by data. Now I can find item only by string:
@
//item data structure
struct ItemData
{
ItemData():Id(-1){}
int Id;
QString name;
};
Q_DECLARE_METATYPE(ItemData)//create model and set it to the combo boxes
QStandardItemModel *model = new QStandardItemModel();
comboBox1->setModel(model);
comboBox2->setModel(model);//insert items
for (int i = 0 ; i < 5 ; ++i) {
//item data
ItemData d;
d.Id=i;
d.name = "Item number" + QString::number(i+1);
//item
QStandardItem *item = new QStandardItem(d.name);
item->setData(QVariant::fromValue(d));
item->setEnabled(d.Id != 2);
//insert
model->appendRow(item);
}//find and remove one item
QList<QStandardItem*> list = model->findItems("Item number 2");
if ( !list.isEmpty() ){
model->removeRow(list[0]->row());
}
@The item searching doesn't look good...
Is there any way to search model item by data? -
You could simply iterate over the model yourself. Then, you can compare on any role you want.