qcomboboxのセパレーター用のスタイルシートを追加する方法

StackOverflow https://stackoverflow.com/questions/19828160

  •  20-07-2022
  •  | 
  •  

質問

セパレーター付きのqcomboboxに2つのアイテムを追加しました

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

さまざまなスタイルのアイテムの選択を強調するために、QListViewをQCOMBOBOXビューにStyleSheetで使用しました。

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

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

これで問題は、セパレーターがまったく見えないことです。アイテムの間に空の空白が表示されています。私はStyleSheetsが苦手なので、セパレーターのために新しいスタイルシートを作る方法についてあまり明確な考えを持っていません。

役に立ちましたか?

解決

カスタムを作成する必要があります itemDelegate あなたのための 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);.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top