任意选择的 QTreeWidgetItems 的样式悬停和选定颜色

Jac*_*ieg 1 qt stylesheet qtreewidget qtreewidgetitem qstyle

我有一个QTreeWidget并且我有一个应用于它的样式表。我希望其中一些QTreeWidgetItem具有与其他样式表样式项目不同的颜色hover和颜色。selectednormal为状态着色setData(columnNumber, Qt::ForegroundRole, colorName),但无法更改悬停和选定状态的颜色。

有谁知道是否可以通过Qt某种方式实现这一目标?

谢谢!

Che*_*byl 5

AFAIK 样式表并不是万能的。你想要非常具体的东西,所以你应该更深入地研究并使用更强大的东西。我建议你使用委托。你没有提供规范,所以我提供主要想法。在QStyledItemDelegate子类中重新实现paint。例如:

void ItemDelegatePaint::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QString txt = index.model()->data( index, Qt::DisplayRole ).toString();

    if( option.state & QStyle::State_Selected )//it is your selection
    {
        if(index.row()%2)//here we try to see is it a specific item
            painter->fillRect( option.rect,Qt::green );//special color
        else
            painter->fillRect( option.rect, option.palette.highlight() );
        painter->drawText(option.rect,txt);//text of item
    } else
    if(option.state & QStyle::State_MouseOver)//it is your hover
    {
        if(index.row()%2)
            painter->fillRect( option.rect,Qt::yellow );
        else
            painter->fillRect( option.rect, Qt::transparent );
        painter->drawText(option.rect,txt);
    }
    else
    {
        QStyledItemDelegate::paint(painter,option,index);//standard process
    }

}
Run Code Online (Sandbox Code Playgroud)

在这里,我为每隔一个项目设置了一些特定属性,但您可以使用其他特定项目。

QTreeWidget继承QTreeView所以使用:

ui->treeWidget->setItemDelegate(new ItemDelegatePaint);
Run Code Online (Sandbox Code Playgroud)

看来你的小部件很复杂,所以我希望你理解主要思想,并且能够编写绝对适合你的委托。如果您以前没有使用过委托,那么请检查示例,它并不是很复杂。

http://qt-project.org/doc/qt-4.8/itemviews-stardelegate-stardelegate-h.html

http://qt-project.org/doc/qt-4.8/itemviews-stardelegate-stardelegate-cpp.html

在我的回答中,我使用了下一个代表:

#ifndef ITEMDELEGATEPAINT_H
#define ITEMDELEGATEPAINT_H

#include <QStyledItemDelegate>
class ItemDelegatePaint : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit ItemDelegatePaint(QObject *parent = 0);
    ItemDelegatePaint(const QString &txt, QObject *parent = 0);


protected:
    void paint( QPainter *painter,
                const QStyleOptionViewItem &option,
                const QModelIndex &index ) const;
    QSize sizeHint( const QStyleOptionViewItem &option,
                    const QModelIndex &index ) const;
    QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    void setEditorData(QWidget * editor, const QModelIndex & index) const;
    void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const;
    void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const;

signals:

public slots:

};

#endif // ITEMDELEGATEPAINT_H
Run Code Online (Sandbox Code Playgroud)

这里有很多方法,但paint对您来说最重要。