49 lines
2.1 KiB
C++
49 lines
2.1 KiB
C++
#include "CustomFileDelegate.h"
|
|
|
|
#include "FileExplorer.h"
|
|
CustomFileDelegate::CustomFileDelegate(FileExplorer* fileExplorer, QObject* parent): QStyledItemDelegate(parent) {
|
|
this->fileExplorer = fileExplorer;
|
|
}
|
|
void CustomFileDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
|
|
// 获取数据
|
|
QFileSystemModel *model = qobject_cast<QFileSystemModel *>(const_cast<QAbstractItemModel *>(index.model()));
|
|
if (!model) {
|
|
QStyledItemDelegate::paint(painter, option, index);
|
|
return;
|
|
}
|
|
|
|
QString fileName = model->fileName(index); // 文件/文件夹名称
|
|
QFileInfo fileInfo = model->fileInfo(index); // 文件/文件夹信息
|
|
QIcon fileIcon = model->fileIcon(index); // 文件/文件夹图标
|
|
|
|
// 设置选中和未选中背景颜色
|
|
QColor background_color = fileInfo.isDir() ? QColor(220, 240, 255) : QColor(255, 255, 220); // 文件夹和文件的不同背景色
|
|
if (option.state & QStyle::State_Selected) {
|
|
background_color = QColor(0, 120, 215); // 选中的背景色
|
|
}
|
|
|
|
// 绘制背景
|
|
painter->fillRect(option.rect, background_color);
|
|
|
|
// 设置文本颜色
|
|
QColor textColor = (option.state & QStyle::State_Selected) ? Qt::white : Qt::black;
|
|
|
|
// 绘制图标
|
|
QRect iconRect = option.rect;
|
|
iconRect.setWidth(fileExplorer->height); // 图标宽度
|
|
fileIcon.paint(painter, iconRect, Qt::AlignVCenter | Qt::AlignLeft);
|
|
|
|
// 绘制文件名
|
|
QRect textRect = option.rect;
|
|
textRect.setLeft(iconRect.right() + 5); // 图标右侧开始绘制文本
|
|
painter->setPen(textColor);
|
|
painter->drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, fileName);
|
|
|
|
// 调用父类实现绘制焦点等其他内容
|
|
//QStyledItemDelegate::paint(painter, option, Windex);
|
|
}
|
|
QSize CustomFileDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const {
|
|
QSize defaultSize = QStyledItemDelegate::sizeHint(option, index);
|
|
return QSize(defaultSize.width(), fileExplorer->height); // 自定义行高
|
|
}
|