문제

I have subclassed QTreeView and made model subclassed from QAbstractTableModeland everything works fine. If something is being changed in QTreeView from code (not by user), then that row's text color becomes red. I have implemented this trough checking Qt::TextColorRole from data() function and returning Qt::red.

But if that particular row is being selected, then text color changes automatically to black (and background color to light green, which is normal). After deselecting that row everything is OK again. In debug mode I've seen that data() function returns true value for selected row (Qt::red).

Now how can I solve this problem, what may cause to this incorrect behaviour?

Thank you in advance!

도움이 되었습니까?

해결책

I've found a way of doing this trough a delegate. Here is the code

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

And for using delegate you should write something like this

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

where pTable's type is QTableView*;

다른 팁

Does the following code keep your text color red?

QPalette p = view->palette();
p.setColor(QPalette::HighlightedText, QColor(Qt::red));
view->setPalette(p);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top