gpt4 book ai didi

c++ - QTreeView选择清除文本颜色

转载 作者:行者123 更新时间:2023-12-03 12:51:10 26 4
gpt4 key购买 nike

我已经对 QTreeView 进行了子类化,并从 QAbstractTableModel 进行了模型子类化,一切正常。如果代码(而不是用户)在 QTreeView 中更改了某些内容,则该行的文本颜色将变为红色。我已经通过从 data() 函数检查 Qt::TextColorRole 并返回 Qt::red 来实现此槽。

但是,如果选择该特定行,则文本颜色会自动更改为黑色(背景颜色更改为浅绿色,这是正常的)。取消选择该行后,一切都恢复正常。在 Debug模式下,我看到 data() 函数返回所选行的真值 (Qt::red)。

现在我该如何解决这个问题,什么可能导致这种不正确的行为?

提前谢谢您!

最佳答案

我找到了一种通过委托(delegate)来完成此操作的方法。这是代码

class TextColorDelegate: public QItemDelegate
{
public:
explicit TextColorDelegate(QObject* parent = 0) : QItemDelegate(parent)
{ }

void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
QStyleOptionViewItem ViewOption(option);

QColor itemForegroundColor = index.data(Qt::ForegroundRole).value<QColor>();
if (itemForegroundColor.isValid())
{
if (itemForegroundColor != option.palette.color(QPalette::WindowText))
ViewOption.palette.setColor(QPalette::HighlightedText, itemForegroundColor);

}
QItemDelegate::paint(painter, ViewOption, index);
}
};

为了使用委托(delegate),你应该写这样的东西

pTable->setItemDelegate(new TextColorDelegate(this));

其中pTable的类型是QTableView*

关于c++ - QTreeView选择清除文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com