i added two items in a qcombobox with a separator
addItem("New");
addItem("Delete");
insertSeparator(2);
in order to highlight the selection of item with different style i used QLIstView for the QComboBox view with the stylesheet as
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 the separator is not visible at all .. it is showing a empty white space between the items . I'm not good with stylesheets so I don't have much clear idea about how to make a new stylesheet for the separator ..
You will have to create a custom itemDelegate
for your QListView
.
You can subclass QItemDelegate
to create your own delegate class. Use sizeHint
function to set the size of your separator and paint it in the paint
function. Check if the items is a separator with 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 );
}
Then just set your custom delegate to your listView
:
listView->setItemDelegate(new ComboBoxDelegate);
.