64 lines
1.8 KiB
C++
64 lines
1.8 KiB
C++
#pragma once
|
|
|
|
#include <QPainter>
|
|
#include <QTableWidgetItem>
|
|
#include <QStyledItemDelegate>
|
|
#include "common.h"
|
|
|
|
#pragma execution_character_set("utf-8")
|
|
|
|
|
|
// 设置某个单元格的边框状态
|
|
void setItemBorderFlags(QTableWidgetItem *item, BorderFlags flags) {
|
|
item->setData(Qt::UserRole, static_cast<int>(flags));
|
|
}
|
|
|
|
// 获取边框状态
|
|
BorderFlags getItemBorderFlags(const QTableWidgetItem *item) {
|
|
return static_cast<BorderFlags>(item->data(Qt::UserRole).toInt());
|
|
}
|
|
|
|
class ItemBorderDelegate : public QStyledItemDelegate {
|
|
public:
|
|
using QStyledItemDelegate::QStyledItemDelegate;
|
|
|
|
void paint(QPainter *painter, const QStyleOptionViewItem &option,
|
|
const QModelIndex &index) const override {
|
|
// 1. 绘制默认内容(文本、图标等)
|
|
QStyledItemDelegate::paint(painter, option, index);
|
|
|
|
const QTableWidget* ptabWgt = qobject_cast<QTableWidget*>(const_cast<QWidget*>(option.widget));
|
|
if (!ptabWgt) return;
|
|
// 2. 获取该单元格存储的边框标志
|
|
QTableWidgetItem *item = ptabWgt->item(index.row(), index.column());
|
|
if (!item) return;
|
|
|
|
BorderFlags flags = getItemBorderFlags(item);
|
|
if (flags == NoBorder) return;
|
|
|
|
// 3. 准备绘制边框
|
|
painter->save();
|
|
painter->setPen(QPen(Qt::black, 2)); // 颜色、宽度可自定义
|
|
QRect rect = option.rect;
|
|
rect.setLeft(rect.left() + 1);
|
|
rect.setTop(rect.top() + 1);
|
|
// 上边框
|
|
if (flags & TopBorder) {
|
|
painter->drawLine(rect.topLeft(), rect.topRight());
|
|
}
|
|
// 下边框
|
|
if (flags & BottomBorder) {
|
|
painter->drawLine(rect.bottomLeft(), rect.bottomRight());
|
|
}
|
|
// 左边框
|
|
if (flags & LeftBorder) {
|
|
painter->drawLine(rect.topLeft(), rect.bottomLeft());
|
|
}
|
|
// 右边框
|
|
if (flags & RightBorder) {
|
|
painter->drawLine(rect.topRight(), rect.bottomRight());
|
|
}
|
|
|
|
painter->restore();
|
|
}
|
|
}; |