how to add stylesheet for separator in QCombobox

前端 未结 1 1927
不知归路
不知归路 2021-01-21 12:52

i added two items in a qcombobox with a separator

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

in order to highlight the selecti

相关标签:
1条回答
  • 2021-01-21 13:44

    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);.

    0 讨论(0)
提交回复
热议问题