问题:
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
所以我被卡住了......
答案 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
视图:
祝你有愉快的一天! :)
PS:不需要重绘图标,文字,选择......
答案 1 :(得分:1)
委托的绘画方法是全部或全部,所以你将无法将你的背景与默认实现混合。
但是,如果你有足够的能力甚至考虑编写一个自定义代表,你可以毫无困难地实现一个可以绘制背景加上图标和文字的代理。