Delegate辅助绘制
void ShareeSignatureDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { // 沿用父类的绘制效果 QStyledItemDelegate::paint(painter, option, index); painter->save(); // 从mode的data接口里根据role获取姓名和签名内容(NameRole,SignatureRole为data接口里自定义的角色名) QString sharerName = index.data(NameRole).toString(); QString signature = index.data(SignatureRole).toString(); QStyleOptionViewItemV4 optV4 = option; initStyleOption(&optV4, index); const QWidget *widget = optV4.widget; QStyle *style = widget ? widget->style() : QApplication::style(); QRect rect = style->subElementRect(QStyle::SE_ItemViewItemText, &optV4, widget); // 定义起始位置 rect = rect.adjusted(5, 0, 0, - optV4.rect.height() / 2); // 设置文字的长度,以及文字过长时的省略模式 QFontMetrics fontMetrics = painter->fontMetrics(); QString elidedNameLine = fontMetrics.elidedText(sharerName, Qt::ElideMiddle, rect.width()); QString elidedSignatureLine = fontMetrics.elidedText(signature, Qt::ElideMiddle, rect.width()); // 执行文字绘制 style->drawItemText(painter, rect, Qt::AlignBottom, QApplication::palette(), true, elidedNameLine); // 设置签名内容的位置,使得该内容在姓名的下方 rect.moveTop(rect.bottom()); painter->setPen(QColor("#949fa5")); if(!signature.isEmpty()) style->drawItemText(painter, rect, Qt::AlignVCenter, QApplication::palette(), true, elidedSignatureLine); else style->drawItemText(painter, rect, Qt::AlignVCenter, QApplication::palette(), true, "无T签?名?信?息¢"); painter->restore(); }
效果图如下: