目录
问题描述
做UI的时候,我们很多时候需要给绘制一个圆角边框,初识Qt绘制的童鞋,可能绘制出来的圆角边框很是锯齿,而且粗细不均匀,如下图:
解决方案
方案1:
给目标widget添加margin,且paintEvent中的绘制区域用contentsRect:
cpp
CustomWidget::NKCustomWidget(QWidget *parent)
: QWidget(parent)
{
m_dWidth = 5.0;
setContentsMargins(1.0, 1.0, 1.0, 1.0);
}
void CustomWidget::paintEvent(QPaintEvent *event)
{
QPainter paint(this);
paint.setRenderHints(QPainter::Antialiasing);
QPainterPath pathBorder;
QRectF rcFrame = contentsRect();
QRectF rcBoder = rcFrame;
pathBorder.addRoundedRect(rcBoder, 24, 24);
QPen pen(Qt::red, m_dWidth);
paint.setPen(pen);
paint.drawPath(pathBorder);
}
方案2:
将绘制区域缩小边框宽度的像素范围
参考代码:
cpp
void NKCustomWidget::paintEvent(QPaintEvent *event)
{
QPainter paint(this);
paint.setRenderHints(QPainter::Antialiasing);
QPainterPath pathBorder;
QRectF rcFrame = contentsRect();
QRectF rcBoder = rcFrame.marginsRemoved(QMarginsF(m_dWidth/2, m_dWidth/2, m_dWidth/2, m_dWidth/2));
pathBorder.addRoundedRect(rcBoder, 24, 24);
QPen pen(Qt::red, m_dWidth);
paint.setPen(pen);
paint.drawPath(pathBorder);
}