【发布时间】:2010-03-12 16:10:28
【问题描述】:
我有一个 QTableView,我正在设置一个自定义 QStyledItemDelegate。
除了自定义项目绘画之外,我还想为选择/悬停状态设置行的背景颜色。我想要的外观类似于此 KGet 屏幕截图: KGet's Row Background http://www.binaryelysium.com/images/kget_background.jpeg
这是我的代码:
void MyDelegate::paint( QPainter* painter, const QStyleOptionViewItem& opt, const QModelIndex& index ) const
{
QBrush backBrush;
QColor foreColor;
bool hover = false;
if ( opt.state & QStyle::State_MouseOver )
{
backBrush = opt.palette.color( QPalette::Highlight ).light( 115 );
foreColor = opt.palette.color( QPalette::HighlightedText );
hover = true;
}
QStyleOptionViewItemV4 option(opt);
initStyleOption(&option, index);
painter->save();
const QStyle *style = option.widget ? option.widget->style() : QApplication::style();
const QWidget* widget = option.widget;
if( hover )
{
option.backgroundBrush = backBrush;
}
painter->save();
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, widget);
painter->restore();
switch( index.column() )
{
case 0: // we want default behavior
style->drawControl(QStyle::CE_ItemViewItem, &option, painter, widget);
break;
case 1:
// some custom drawText
break;
case 2:
// draw a QStyleOptionProgressBar
break;
}
painter->restore();
}
结果是每个单独的单元格仅在鼠标悬停在其上时才会接收到 mousedover 背景,而不是整行。很难描述,所以这里是截图: The result of the above code http://www.binaryelysium.com/images/loader_bg.jpeg
在那张图片中,鼠标位于最左侧的单元格上,因此背景突出显示..但我希望将背景绘制在整行上。
我怎样才能做到这一点?
编辑:经过更多思考,我意识到 QStyle::State_MouseOver 状态仅被传递给鼠标所在的实际单元格,并且当为行 QStyle:: 中的其他单元格调用paint方法时State_MouseOver 未设置。
所以问题变成了是否存在 QStyle::State_MouseOver_Row 状态(答案:否),那么我该如何实现呢?
【问题讨论】:
-
也许我需要重新实现我的 qtableview,并覆盖paintevent?
标签: c++ qt qitemdelegate