Seb*_*anK 9 c++ user-interface qt qtreeview
我有一个QTreeView
并且想要行的不同背景颜色,具体取决于它们的内容.为实现这一目标,我从中派生了一个class MyTreeView
from QTreeView
并实现了paint方法,如下所示:
void MyTreeView::drawRow (QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const
{
QStyleOptionViewItem newOption(option);
if (someCondition)
{
newOption.palette.setColor( QPalette::Base, QColor(255, 0, 0) );
newOption.palette.setColor( QPalette::AlternateBase, QColor(200, 0, 0) );
}
else
{
newOption.palette.setColor( QPalette::Base, QColor(0, 0, 255) );
newOption.palette.setColor( QPalette::AlternateBase, QColor(0, 0, 200) );
}
QTreeView::drawRow(painter, newOption, index);
}
Run Code Online (Sandbox Code Playgroud)
最初,我设置setAlternatingRowColors(true);
了QTreeView.
我的问题:为QPalette :: Base设置颜色没有任何效果.每隔一行保持白色.
但是,设置QPalette :: AlternateBase按预期工作.我试着setAutoFillBackground(true)
和setAutoFillBackground(false)
无任何影响.
有没有提示如何解决这个问题?谢谢.
备注:通过调整MyModel::data(const QModelIndex&, int role)
来设置颜色Qt::BackgroundRole
不能提供所需的结果.在这种情况下,背景颜色仅用于行的一部分.但我想为整行着色,包括左侧的树导航内容.
Qt版本: 4.7.3
更新:
由于未知原因QPalette::Base
似乎不透明.setBrush不会改变它.我找到了以下解决方法:
if (someCondition)
{
painter->fillRect(option.rect, Qt::red);
newOption.palette.setBrush( QPalette::AlternateBase, Qt::green);
}
else
{
painter->fillRect(option.rect, Qt::orange);
newOption.palette.setBrush( QPalette::AlternateBase, Qt:blue);
}
Run Code Online (Sandbox Code Playgroud)
如果唯一的问题是扩张/折叠控件没有像行,然后利用休息背景Qt::BackgroundRole
在::data()
你的模型(如由pnezis在他们的答案),并添加到您的树视图类:
void MyTreeView::drawBranches(QPainter* painter,
const QRect& rect,
const QModelIndex& index) const
{
if (some condition depending on index)
painter->fillRect(rect, Qt::red);
else
painter->fillRect(rect, Qt::green);
QTreeView::drawBranches(painter, rect, index);
}
Run Code Online (Sandbox Code Playgroud)
我已经在Windows(Vista和7)上使用Qt 4.8.0进行了测试,并且扩展/折叠箭头具有适当的背景.问题是这些箭头是视图的一部分,因此无法在模型中处理.
QTreeView
您应该通过模型处理背景颜色,而不是子类化.使用该data()
功能和Qt::BackgroundRole
更改行的背景颜色.
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::BackgroundRole)
{
if (condition1)
return QColor(Qt::red);
else
return QColor(Qt::green);
}
// Handle other roles
return QVariant();
}
Run Code Online (Sandbox Code Playgroud)