Drawing Rectangle with only 2 corners rounded
一、效果
二、实现原理
使用QPainterPath合并addRoundedRect和addRect的path形成目标path。然后使用painter填充绘制path即可。
三、实现代码
自定义类继承QWidget并实现如下方法:
void paintEvent(QPaintEvent *event) override;
然后在paintEvent函数内调用如下绘制函数即可。
void XXX::DrawInfoBar(QPainter &painter) {
Q_UNUSED(painter)
QString text = "this is a test string haha wahaha !";
int text_draw_width = painter.fontMetrics().width(text);
text_draw_width += 50;//add space
//set drawing position with a rect
int x = 50;
int width = text_draw_width;//300;
QRect info_rect(x, 0, width, 24);
QPainterPath path;
path.setFillRule( Qt::WindingFill );
path.addRoundedRect (info_rect, 10.0, 10.0);
QRect temp_rect(info_rect.left(), info_rect.top(), info_rect.width(), info_rect.height()/2);
path.addRect(temp_rect);
painter.fillPath(path, QBrush(QColor(93, 201, 87)));
//draw text in the half-round-rect
QTextOption option;
option.setAlignment(Qt::AlignCenter);
painter.drawText(info_rect, text, option);
}