Search code examples
c++qtqcombobox

Grouped QComboBox


Could you show me a simple example of how to make this grouped combobox in Qt?

enter image description here


Solution

  • You can find the description how to do this here:

    http://web.archive.org/web/20170826190441/mimec.org/node/305

    The idea is that you add parent items and child items and then they are painted differently with the help of custom delegate.

    I.e. you set

    item->setData( "parent", Qt::AccessibleDescriptionRole );
    

    when adding parent item of group and

    item->setData( "child", Qt::AccessibleDescriptionRole );
    

    otherwise.

    And then you use this information for painting:

    if ( type == QLatin1String( "parent" ) ) {
            QStyleOptionViewItem parentOption = option;
            parentOption.state |= QStyle::State_Enabled;
            QItemDelegate::paint( painter, parentOption, index );
        } 
        else if ( type == QLatin1String( "child" ) ) {
            QStyleOptionViewItem childOption = option;
            int indent = option.fontMetrics.width( QString( 4, QChar( ' ' ) ) );
            childOption.rect.adjust( indent, 0, 0, 0 );
            childOption.textElideMode = Qt::ElideNone;
            QItemDelegate::paint( painter, childOption, index );
        }