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

标签 c++ qt selection qtreeview

我已经对 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/

相关文章:

c++ - 在我的 C++/STL/MFC 应用程序启动早期发生的致命异常中,我可以信任堆栈回溯符号名称吗?

Qt 检查 QString 以查看它是否是有效的十六进制值

qt - 关于QGraphicsItem的 'itemChange()'的一个问题

excel - 将选定范围复制到另一个工作表

c++ - RccpGSL,在 Windows 7 上从 R 安装/使用 GSL

c++ - 在 C++ 中使用系统调用可执行文件时参数字符串中的字符丢失

c++ - Qt:类中变量的默认值

apache-flex - Flexlib ScheduleViewer..如何处理项目的点击

c++ - 连接 2 QTableWidget 中的行选择

c++ - 找出 AxB 的网格中有多少圈