How to add a stylesheet for a separator in QCombobox

I added two elements in qcombobox with a separator

addItem("New");
addItem("Delete");
insertSeparator(2);

to highlight the selection of an item with a different style, I used a QLIstView to represent a QComboBox with a style like

QListView * listView = new QListView(this);
this->setView(listView);

listView->setStyleSheet("QListView::item {                              \
                            color: black;                                    \
                            background: white;                           }  \
                            QListView::item:selected {                     \
                            color: white;                                  \
                            background-color: #0093D6  \
                            }                                               \
                            ");

now the problem is that the separator is not visible at all .. it shows the empty empty space between the elements. I'm not good at style sheets, so I don't have a clear idea of โ€‹โ€‹how to create a new stylesheet for the separator.

+2
source share
1 answer

You need to create a custom one itemDelegatefor QListView.

QItemDelegate . sizeHint, paint. , index.data(Qt::AccessibleDescriptionRole).toString().

#ifndef COMBOBOXDELEGATE_H
#define COMBOBOXDELEGATE_H

#include <QItemDelegate>

class ComboBoxDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    explicit ComboBoxDelegate(QObject *parent = 0);

protected:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
};

#endif // COMBOBOXDELEGATE_H

void ComboBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(index.data(Qt::AccessibleDescriptionRole).toString() == QLatin1String("separator"))
    {
        painter->setPen(Qt::red);
        painter->drawLine(option.rect.left(), option.rect.center().y(), option.rect.right(), option.rect.center().y());
    }
    else
        QItemDelegate::paint(painter, option, index);
}

QSize ComboBoxDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QString type = index.data(Qt::AccessibleDescriptionRole).toString();
    if(type == QLatin1String("separator"))
        return QSize(0, 2);
    return QItemDelegate::sizeHint( option, index );
}

listView:

listView->setItemDelegate(new ComboBoxDelegate);.

+5

Source: https://habr.com/ru/post/1613658/


All Articles