【问题标题】:Change text color of a specific column for QTreeView更改 QTreeView 特定列的文本颜色
【发布时间】:2018-04-29 00:43:20
【问题描述】:

我有从 QTreeView 继承的小部件,我想更改文本颜色,但仅限于特定列。目前我设置了样式表,所以当项目被选中时,整行将文本颜色更改为红色。

QTreeView::item:selected {color: red}

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

【问题讨论】:

  • QTreeWidget 还是 QTreeView?
  • 对不起,QTreeView...我会改的

标签: qt stylesheet selecteditem qtreewidget


【解决方案1】:

您可以为此使用委托:

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】:

所以这就是我解决它的方法。

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

【讨论】:

    猜你喜欢
    • 2016-02-02
    • 2013-04-17
    • 2012-03-13
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    相关资源
    最近更新 更多