如何使用QStyledItemDelegate绘制不同的背景?

时间:2012-05-25 16:16:07

标签: qt qt4 qstyleditemdelegate

问题

  • 我有QTreeView个对象,QStandardItemModel作为模型来查看小部件;
  • 对于某些项目,我使用setData方法设置数据以使用参数对其进行拆分;
  • 所以我需要为QStandardItem项目绘制不同的背景 pixmap ,这些项目带有图标和一些文字数据;
  • 并且不要想要重绘所有项目对象,我的意思是图标和文字。只需改变背景。

首先,我在想:

  • 我可以在Qt Designer中为具有2张不同背景图片的对象设置CSS样式表,但是 QStandardItem 没有 {{1方法......

示例:

setProperty
  • 然后我创建了自己的委托,继承自QTreeView#treeView::item[ROLE="AAA"], QTreeView#treeView::branch[ROLE="AAA"] { height: 25px; border: none; color: #564f5b; background-image: url(:/backgrounds/images/row1.png); background-position: top left; } QTreeView#treeView::item[ROLE="BBB"], QTreeView#treeView::branch[ROLE="BBB"] { height: 25px; border: none; color: #564f5b; background-image: url(:/backgrounds/images/row2.png); background-position: top left; } 类,重新实现QStyledItemDelegate方法,我不能只改变背景,因为paint代码将覆盖我的QStyledItemDelegate::paint( painter, opt, index ); ...

示例:

drawPixmap

所以我被卡住了......

2 个答案:

答案 0 :(得分:6)

这是我的诀窍:

Designer的样式表部分:

QTreeView#treeView
{
    border: none;
    background-color:#f0f0f1;
}   

QTreeView#treeView::item,
QTreeView#treeView::branch
{
    height: 25px;
    border: none;
    color: #564f5b;
}

QTreeView#treeView::item:selected,
QTreeView#treeView::branch:selected
{
    border-bottom: none;
    color: #ffffff;    
    background-image: url(:/backgrounds/images/backgrounds/kontragents_row_selection.png);
    background-position: top left;  

}

QTreeView#treeView::item:selected:!active,
QTreeView#treeView::branch:selected:!active
{
    color: #ffffff;
}

委派重新实现的paint()方法:

void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
 {
      QStyleOptionViewItemV4 opt = option; // Для обхода QTBUG-4310
      opt.state &= ~QStyle::State_HasFocus; // Чтобы не рисовался прямоугольник фокуса

      QBrush brush = opt.backgroundBrush;
      brush.setTexture( QPixmap( index.data( SORT_ROLE ).toBool()
           ? BACKGROUND_HIGH_PRIORITY
           : BACKGROUND_STANDARD ) );

      // FILL BACKGROUND     
      painter->save();
      painter->fillRect( opt.rect, brush );
      painter->restore();

      // DRAW ICON & TEXT
      QStyledItemDelegate::paint( painter, opt, index );

      // IF ( CHILD ) THEN PAINT OVER ONLY! BRANCH RECT
      bool isIndexParent = !index.parent().isValid();
      if( !isIndexParent )
      {
           QRect rect( 0, opt.rect.y(), 20, opt.rect.height() );

           if( opt.state & QStyle::State_Selected )
           {
                brush.setTexture( QPixmap( BACKGROUND_SELECTED ) );
           }

           painter->save();
           painter->fillRect( rect, brush );
           painter->restore();
      }
 }

结果QTreeView视图:

enter image description here

祝你有愉快的一天! :)

PS:不需要重绘图标,文字,选择......

答案 1 :(得分:1)

委托的绘画方法是全部或全部,所以你将无法将你的背景与默认实现混合。

但是,如果你有足够的能力甚至考虑编写一个自定义代表,你可以毫无困难地实现一个可以绘制背景加上图标和文字的代理。