1.创建继承QStyledItemDelegate的类。
ScreenTreeWidgetItemDelegate::ScreenTreeWidgetItemDelegate(ScreenTreeWidget *parent):
QStyledItemDelegate(parent),
m_handler(parent)
{
}
2. 在创建的 类中实现paint函数,所有单元格的画的内容都在paint函数里来画
void ScreenTreeWidgetItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(!index.data(Qt::UserRole).toBool())
return;
QRect rect = option.rect;
rect.setHeight(rect.height()-1);
painter->fillRect(rect, QColor(39,44,60));
painter->setPen(Qt::white);
QTextOption op;
op.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
painter->drawText(option.rect, index.data(Qt::DisplayRole).toString(), op);
QRect iconRect(10,option.rect.y()+(option.rect.height()-16)/2,16,16);
if(m_handler->isExpanded(index))
{
if(option.state & QStyle::State_MouseOver)
{
QImage img(":/image/open_hover");
painter->drawImage(iconRect, img, img.rect());
}
else
{
QImage img(":/image/open");
painter->drawImage(iconRect, img, img.rect());
}
}
else
{
if(option.state & QStyle::State_MouseOver)
{
QImage img(":/image/close_hover");
painter->drawImage(iconRect, img, img.rect());
}
else
{
QImage img(":/image/close");
painter->drawImage(iconRect, img, img.rect());
}
}
}
3.使用,在使用类中设置
setItemDelegate(new ScreenTreeWidgetItemDelegate(this));