49 lines
2.1 KiB
C++
49 lines
2.1 KiB
C++
#include "CustomFileDelegate.h"
|
|
|
|
#include "FileExplorer.h"
|
|
Custom_File_Delegate::Custom_File_Delegate(file_explorer* fileExplorer, QObject* parent): QStyledItemDelegate(parent) {
|
|
this->fileExplorer = fileExplorer;
|
|
}
|
|
void Custom_File_Delegate::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 file_info = model->fileInfo(index); // 文件/文件夹信息
|
|
QIcon file_icon = model->fileIcon(index); // 文件/文件夹图标
|
|
|
|
// 设置选中和未选中背景颜色
|
|
QColor background_color = file_info.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 text_color = (option.state & QStyle::State_Selected) ? Qt::white : Qt::black;
|
|
|
|
// 绘制图标
|
|
QRect icon_rect = option.rect;
|
|
icon_rect.setWidth(fileExplorer->height); // 图标宽度
|
|
file_icon.paint(painter, icon_rect, Qt::AlignVCenter | Qt::AlignLeft);
|
|
|
|
// 绘制文件名
|
|
QRect text_rect = option.rect;
|
|
text_rect.setLeft(icon_rect.right() + 5); // 图标右侧开始绘制文本
|
|
painter->setPen(text_color);
|
|
painter->drawText(text_rect, Qt::AlignVCenter | Qt::AlignLeft, fileName);
|
|
|
|
// 调用父类实现绘制焦点等其他内容
|
|
//QStyledItemDelegate::paint(painter, option, Windex);
|
|
}
|
|
QSize Custom_File_Delegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const {
|
|
QSize default_size = QStyledItemDelegate::sizeHint(option, index);
|
|
return QSize(default_size.width(), fileExplorer->height); // 自定义行高
|
|
}
|