如上图,左上角和右上角凸出来了。设置表格圆角和表头圆角和QHeaderView::section圆角都不管用。解决此问题需要重写QHeaderView的paintSection()函数:
class CustomHeaderView : public QHeaderView
{
public:explicit CustomHeaderView(Qt::Orientation orientation, QWidget *parent = nullptr) : QHeaderView(orientation, parent) {}
private:int radius{6};//圆角
protected:void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override{painter->save();painter->setRenderHint(QPainter::Antialiasing, true);if(logicalIndex == 0){QPainterPath path;path.addRoundedRect(rect,radius,radius);QRect tempRect;tempRect = rect;tempRect.setTopLeft(QPoint(rect.width()/2,0));QPainterPath path_tempRect;path_tempRect.addRect(tempRect);path += path_tempRect;tempRect = rect;tempRect.setTopLeft(QPoint(0,rect.height()/2));path_tempRect.clear();path_tempRect.addRect(tempRect);path += path_tempRect;painter->setClipPath(path);painter->fillPath(path,Qt::white);}else if(logicalIndex == (count() - 1)){QPainterPath path;path.addRoundedRect(rect,radius,radius);QRect tempRect;tempRect = rect;tempRect.setTopRight(QPoint(rect.x() + rect.width()/2,0));QPainterPath path_tempRect;path_tempRect.addRect(tempRect);path += path_tempRect;tempRect = rect;tempRect.setTopRight(QPoint(rect.x() + rect.width(),rect.height()/2));path_tempRect.clear();path_tempRect.addRect(tempRect);path += path_tempRect;painter->setClipPath(path);painter->fillPath(path,Qt::white);}else{painter->fillRect(rect,Qt::white);}painter->setPen(QPen(QColor(192, 192, 192),1));if (logicalIndex != 0){painter->drawLine(rect.topLeft(),rect.bottomLeft());}painter->drawLine(rect.bottomLeft(),rect.bottomRight());// 绘制文字painter->setPen(Qt::black); // 设置文字颜色painter->drawText(rect.adjusted(5, 0, -5, 0), defaultAlignment(), model()->headerData(logicalIndex, orientation()).toString());painter->restore();}
};
效果: