0

I have a QComboBox with a QStandardItemModel, which contains a single item named One. I want the QComboBox to have an header (I’m not sure this is the correct technical term …) which will always be the same. The following image depicts exactly what I want. Instead of having "One" next to the button that push down the list, I want "Header" printed (which is not an element of the list). enter image description here

Important, the checkbox are mandatory (which is why I'm using QComboBox).

I tried the function model.setHorizontalHeaderItem() but it does not work (see the code below). Please, help me.

#include <QApplication>
#include <QComboBox>
#include <QStandardItemModel>

int main( int argc, char **argv )
{
QApplication app( argc, argv );
QComboBox* comboBox = new QComboBox();
QStandardItemModel model( 1, 1 );
QStandardItem *item = new QStandardItem( QString("One") );
item->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled );
item->setData ( Qt::Unchecked, Qt::CheckStateRole );
model.setItem(0, 0, item);
model.setHorizontalHeaderItem( 0, new QStandardItem( "Header" ) );
comboBox->setModel( &model );
comboBox->show();

return app.exec();
}
jp_doyon1
  • 51
  • 4
  • I think you need to create your own model and implement `headerData` member function. All the info you need is here: http://qt-project.org/doc/qt-4.8/model-view-programming.html#model-headers-and-data – Iuliu Oct 23 '14 at 12:57
  • You need to set custom view to display drop-down content with headers. – Dmitry Sazonov Oct 23 '14 at 13:21
  • @DmitrySazonov I don't think he's referring to that header. I think he wants the combo box to display the header, and the dropdown to display the list view without the header...anyway it is unclear what he wants... – Iuliu Oct 23 '14 at 15:04
  • @luliu He wants to have a header. It is clear. Your comment about headerData function is useless. – Dmitry Sazonov Oct 23 '14 at 15:45
  • I tried to explain clearly what I want above. Thanks. – jp_doyon1 Oct 27 '14 at 15:55

1 Answers1

1

You can do something like this:

QTreeView *view = new QTreeView();
QStandardItemModel *model = new QStandardItemModel();

ui->comboBox->setModel( model );
ui->comboBox->setView( view );

for ( int i = 0; i < 10; i++ )
{
    QStandardItem *item = new QStandardItem();
    const QString text = QString( "Item: %1" ).arg( i + 1 );
    item->setText( text );
    model->appendRow( item );
}

model->setHorizontalHeaderLabels( QStringList() << "It's a column" );

You will get something like this: ComboBox with header

Now you can do all customization like with a standard QTreeView.

Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61
  • 1
    No, I deleted my answer. It is not solution. I just show how to set item with color and recommended dirty trick with signals and slots. Your answer is natural for Qt solution. I voted up it earlier. – Jablonski Oct 23 '14 at 17:39