目标
为控件设置圆角,且子控件的显示不会超出圆角范围。
代码实现
QFrame *widget = new QFrame(nullptr);
// 方案一
QBitmap bmp(widget->size());
bmp.clear();
QPainter painter(&bmp);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(Qt::black));
painter.drawRoundedRect(widget->rect(), 8.0f, 8.0f, Qt::AbsoluteSize);
widget->setMask(bmp);
// 方案二(相比于方案一,圆角的锯齿比较明显)
QPainterPath path;
path.addRoundedRect(widget->rect(), 8.0f, 8.0f, Qt::AbsoluteSize);
QRegion region = QRegion(path.toFillPolygon().toPolygon());
widget->setMask(region);
参考链接
https://stackoverflow.com/questions/3829317/non-pixelized-rounded-corner-for-top-level-window