Qt编写自定义控件:自定义表头实现左右两端上部分圆角

Qt编写自定义控件:自定义表头实现左右两端上部分圆角_第1张图片

如上图,左上角和右上角凸出来了。设置表格圆角和表头圆角和QHeaderView::section圆角都不管用。解决此问题需要重写QHeaderViewpaintSection()函数: 

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();
    }
};

效果:

Qt编写自定义控件:自定义表头实现左右两端上部分圆角_第2张图片

你可能感兴趣的:(#,Qt编写自定义控件,#,Qt样式表,qt)