【问题标题】:QTreeView selection clears text colorQTreeView 选择清除文本颜色
【发布时间】:2013-10-14 14:22:47
【问题描述】:

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

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

现在我该如何解决这个问题,可能导致这种错误行为的原因是什么?

提前谢谢你!

【问题讨论】:

    标签: c++ qt selection qtreeview


    【解决方案1】:

    我通过委托找到了一种方法。这是代码

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

    对于使用委托,你应该写这样的东西

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

    其中pTable 的类型是QTableView*

    【讨论】:

      【解决方案2】:

      以下代码是否使您的文本颜色保持红色?

      QPalette p = view->palette();
      p.setColor(QPalette::HighlightedText, QColor(Qt::red));
      view->setPalette(p);
      

      【讨论】:

      • 实际上这会像每次一样更改突出显示的文本颜色,但是我需要在更改特定行的文本颜色时更改它。
      猜你喜欢
      • 2014-12-17
      • 1970-01-01
      • 2014-02-10
      • 2020-07-15
      • 2023-01-12
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多