1// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5#include "displayitemdelegate.h"
6
7#include <QPainter>
8#include <QDebug>
9#include <QApplication>
10#include <QFileInfo>
11
12DisplayItemDelegate::DisplayItemDelegate(QObject *parent)
13 : QStyledItemDelegate (parent)
14{
15
16}
17
18void DisplayItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
19 const QModelIndex &index) const
20{
21 if (index.isValid()) {
22 int textTopAlign = Qt::AlignmentFlag::AlignTop;
23 int textBottomAlign = Qt::AlignmentFlag::AlignBottom;
24 QString filePath = index.data(Qt::DisplayRole).toString();
25 QString fileName = QFileInfo(filePath).fileName();
26 QStyleOptionViewItem drawStyle(option);
27 initStyleOption(&drawStyle, index);
28 drawStyle.text = ""; //清空文本绘制
29 QStyle *pStyle = drawStyle.widget ? drawStyle.widget->style() : QApplication::style();
30 pStyle->drawControl(QStyle::CE_ItemViewItem, &drawStyle, painter, drawStyle.widget);
31
32
33 QRect iconRect = pStyle->itemPixmapRect(drawStyle.rect, drawStyle.displayAlignment,
34 drawStyle.icon.pixmap(drawStyle.rect.height()));
35 QRect titleTextRect = pStyle->itemTextRect(drawStyle.fontMetrics, drawStyle.rect, textTopAlign, true, fileName)
36 .adjusted(iconRect.width(), 0, 0, 0);
37 titleTextRect.setWidth(option.rect.width());
38
39 QString eliedFileName = drawStyle.fontMetrics.elidedText(fileName, Qt::ElideRight, titleTextRect.width());
40 pStyle->drawItemText(painter, titleTextRect, drawStyle.displayAlignment, drawStyle.palette, true, eliedFileName);
41
42 painter->save();
43
44 //缩小字体
45 QFont nativeFont(drawStyle.font);
46 nativeFont.setPointSize(drawStyle.font.pointSize() - 1);
47 nativeFont.setItalic(true);
48 painter->setFont(nativeFont);
49
50 //计算绘制坐标
51 QRect nativeTextRect = pStyle->itemTextRect(QFontMetrics(nativeFont), drawStyle.rect, textBottomAlign, true, filePath)
52 .adjusted(iconRect.width(), 0, 0, 0);
53 nativeTextRect.setWidth(option.rect.width());
54
55 QString eliedFilePath = drawStyle.fontMetrics.elidedText(filePath, Qt::ElideRight, nativeTextRect.width());
56 painter->drawText(nativeTextRect, textBottomAlign, eliedFilePath);
57 painter->restore();
58 } else {
59 return QStyledItemDelegate::paint(painter, option, index);
60 }
61}
62
63QSize DisplayItemDelegate::sizeHint(const QStyleOptionViewItem &option,
64 const QModelIndex &index) const
65{
66 if (index.isValid()) {
67 QSize size = index.data(Qt::SizeHintRole).toSize();
68 if (size.isValid()) {
69 return size;
70 } else {
71 return {option.rect.width(), option.fontMetrics.height() * 2};
72 }
73 }
74 return QStyledItemDelegate::sizeHint(option, index);
75}
76