代码之家  ›  专栏  ›  技术社区  ›  laurapons

更改QTreeView特定列的文本颜色

  •  2
  • laurapons  · 技术社区  · 7 年前

    我有一个从QTreeView继承的小部件,我想更改文本颜色,但只针对特定列。目前,我设置了样式表,因此当选中项目时,整行将文本颜色更改为红色。

    QTreeView::item:selected {color: red}
    

    我只想在选中项目时更改第一列的颜色。我知道如何更改特定列的颜色(在模型上使用ForegroundRole并检查索引列),但我不知道如何检查是否在模型中选择了索引。

    2 回复  |  直到 7 年前
        1
  •  3
  •   king_nak    7 年前

    您可以使用委托:

    class MyDelegate : public QStyledItemDelegate {
    public:
        void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
            if (option.state & QStyle::State_Selected) {
                QStyleOptionViewItem optCopy = option;
                optCopy.palette.setColor(QPalette::Foreground, Qt::red);
            }
            QStyledItemDelegate::paint(painter, optCopy, index);
        }
    }
    
    myTreeWidget->setItemDelegateForColumn(0, new MyDelegate);
    
        2
  •  1
  •   laurapons    7 年前

    我就是这样解决的。

    class MyDelegate : public QStyledItemDelegate {
    public:
        void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { 
            QString text_highlight;
            if (index.column() == 0)){
                text_highlight = BLUE;
            } else{
                text_highlight = RED;
            }
            QStyleOptionViewItem s = *qstyleoption_cast<const QStyleOptionViewItem*>(&option);
            s.palette.setColor(QPalette::HighlightedText, QColor(text_highlight));
            QStyledItemDelegate::paint(painter, s, index);
        }
    }