2013-10-14 74 views
0

我已经子类QTreeView并从QAbstractTableModel取得模型子类,并且一切正常。如果在代码中(而不是用户)在QTreeView中更改某些内容,那么该行的文本颜色将变为红色。我已经通过从data()函数执行此槽并返回Qt::redQTreeView选择清除文本颜色

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

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

预先感谢您!

回答

0

我发现了一种通过委托来做这件事的方法。下面是代码

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*;

0

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

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

实际上,这会随时更改突出显示的文本颜色,但我需要在更改特定行的文本颜色时进行更改。 – nabroyan