首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用QStandardItem调整QStyledItemDelegate的选择行为

用QStandardItem调整QStyledItemDelegate的选择行为
EN

Stack Overflow用户
提问于 2015-02-13 03:20:53
回答 1查看 754关注 0票数 1

我正在使用QStyledItemDelegateQTreeView中的项目进行样式化。

我的树形视图的根没有装饰。它只是一棵简单的树,其关系类似于下面的一棵:

代码语言:javascript
复制
ColorBook1
    Color1
    Color2
ColorBook2
    Color3

父级和子级的样式不同,父级和父级上的选择被禁用。

我希望自定义子节点中的选择行为,这样围绕子节点的选择矩形将覆盖整个行,而不仅仅是文本子节点。

目前的行为:

期望的行为:

有任何方法来扩展这样的选择矩形使用QStyledItemDelegate吗?我尝试了adjusting rectQStyleOptionViewItem参数中的QStyledItemDelegate::paint。但这会将子节点文本移动到左侧。我希望将文本节点保持在相同的位置,但只有选择矩形必须调整到左边。因此,就像在画图方法中绘制文本和像素映射一样,是否也有一种方法来绘制选择矩形(使用默认的选择-- rect颜色)?

我的StyledItemDelegate的油漆方法如下:

我在QStyledItemDelegate中使用了以下代码::code方法:

代码语言:javascript
复制
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 );
   }
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-13 11:36:46

你可以自己画。使用option.palette.brush(QPalette::Highlight)获取高亮颜色。

在这个片段中,我只是手动绘制空白区域。我也改变了颜色,但你不必这样做。

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28491925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档