我正在使用QStyledItemDelegate对QTreeView中的项目进行样式化。
我的树形视图的根没有装饰。它只是一棵简单的树,其关系类似于下面的一棵:
ColorBook1
Color1
Color2
ColorBook2
Color3父级和子级的样式不同,父级和父级上的选择被禁用。
我希望自定义子节点中的选择行为,这样围绕子节点的选择矩形将覆盖整个行,而不仅仅是文本子节点。
目前的行为:

期望的行为:

有任何方法来扩展这样的选择矩形使用QStyledItemDelegate吗?我尝试了adjusting rect在QStyleOptionViewItem参数中的QStyledItemDelegate::paint。但这会将子节点文本移动到左侧。我希望将文本节点保持在相同的位置,但只有选择矩形必须调整到左边。因此,就像在画图方法中绘制文本和像素映射一样,是否也有一种方法来绘制选择矩形(使用默认的选择-- rect颜色)?
我的StyledItemDelegate的油漆方法如下:
我在QStyledItemDelegate中使用了以下代码::code方法:
void paint( QPainter * inPainter, const QStyleOptionViewItem & inOption, const QModelIndex & inIndex ) const
{
if( inIndex.data( Qt::UserRole ) == ColorInfoType::kColorBook )
{
QFont font = inPainter->font();
font.setWeight( QFont::Bold );
font.setPointSize( 8 );
inPainter->setFont( font );
inPainter->drawText
(
inOption.rect.adjusted( 5,0,0,0 ),
inIndex.data( Qt::DisplayRole ).toString(),
QTextOption( Qt::AlignVCenter | Qt::AlignLeft )
);
}
else
{
//To Do: draw the selection rect after adjusting the size.
// Draw the Color Name text
QStyledItemDelegate::paint( inPainter, inOption, inIndex );
}
}发布于 2015-02-13 11:36:46
你可以自己画。使用option.palette.brush(QPalette::Highlight)获取高亮颜色。
在这个片段中,我只是手动绘制空白区域。我也改变了颜色,但你不必这样做。
void StyleDel::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(option.state.testFlag(QStyle::State_Selected))
{
QStyleOptionViewItem newOption = option;
newOption.state = option.state & (~QStyle::State_HasFocus);
QBrush brush = option.palette.brush(QPalette::Highlight);
brush.setColor(QColor(150,0,0,100));
newOption.palette.setBrush(QPalette::Highlight, brush);
QRect s_rect = newOption.rect; //we use this rect to define the blank area
s_rect.setLeft(0); // starts from 0
s_rect.setRight(newOption.rect.left()); //ends where the default rect starts
painter->fillRect(s_rect, newOption.palette.brush(QPalette::Highlight));
QStyledItemDelegate::paint(painter, newOption, index);
return;
}
QStyledItemDelegate::paint(painter, option, index);
}https://stackoverflow.com/questions/28491925
复制相似问题