I am trying to make the items in a ComboBox
checkable. I tried this:
http://programmingexamples.net/wiki/Qt/ModelView/ComboBoxOfCheckBoxes
where I subclassed QStandardItemModel
and re-implemented the flags()
function to make the items checkable. Then I added this model to the ComboBox
. Unfortunately, a checkbox does not appear with the items. Can anyone see where I have gone wrong?
Have you set a check state as well as making them checkable?
In my example below, this line is critical:
item->setData(Qt::Unchecked, Qt::CheckStateRole);
If it is omitted the check boxes won't render as there isn't a valid check-state to render.
The example shows check boxes in a combobox, list and table, as I couldn't get it to work at first either, so I tried different views.
test.cpp
#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QStandardItemModel model(3, 1); // 3 rows, 1 col
for (int r = 0; r < 3; ++r)
{
QStandardItem* item = new QStandardItem(QString("Item %0").arg(r));
item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
item->setData(Qt::Unchecked, Qt::CheckStateRole);
model.setItem(r, 0, item);
}
QComboBox* combo = new QComboBox();
combo->setModel(&model);
QListView* list = new QListView();
list->setModel(&model);
QTableView* table = new QTableView();
table->setModel(&model);
QWidget container;
QVBoxLayout* containerLayout = new QVBoxLayout();
container.setLayout(containerLayout);
containerLayout->addWidget(combo);
containerLayout->addWidget(list);
containerLayout->addWidget(table);
container.show();
return app.exec();
}
test.pro
QT=core gui
SOURCES=test.cpp