painter->save();
// 获取单元格矩形区域
QRect rect = option.rect;
// 绘制背景
painter->fillRect(rect, option.palette.base());
// 绘制边框
painter->setPen(option.palette.color(QPalette::Mid));
painter->drawRect(rect.adjusted(0, 0, -1, -1)); // 边框向内缩小1px
// 绘制文本
QString text = index.data().toString();
QRect textRect = rect.adjusted(5, 0, -20, 0); // 文字区域,右侧留空给箭头
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, text);
// 箭头的位置和大小(相对于原生下拉框样式)
QRect arrowRect = QRect(rect.right() - 20, rect.top() + rect.height() / 4, 15, rect.height() / 2);
// 设置箭头绘制选项
QStyleOption arrowOption;
arrowOption.rect = arrowRect;
arrowOption.palette = option.palette;
arrowOption.state = QStyle::State_Enabled;
// 使用 QStyle 绘制下拉箭头,确保它与原生 QComboBox 的箭头一致
QApplication::style()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &arrowOption, painter);
painter->restore();
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
// 让表格进入编辑模式
QAbstractItemView* view = qobject_cast<QAbstractItemView*>(parent());
if (view) {
view->edit(index); // Use 'view' here instead of 'view_'
}
return true;
}
}
return QStyledItemDelegate::editorEvent(event, model, option, index);