1. 问题描述
当给QMenu设置样式时,希望使用 border-radius 为 QMenu 设置10px的圆角, 样式表如下:
QMenu{
background-color:rgb(255,255,255);
border-width:1px;
border-color :rgb(0,0,0);
border-radius:10px;
border-style:solid
}
此时可以看到QMenu内部的填充依然是矩形,见红圈标注部分.
解决办法
- 方法1
QMenu是一个矩形的顶层控件,因此需要在实例化QMenu后,设置QMenu实例的窗口属性。
PySide2/PyQt5代码如下:
menu = QMenu()
# 设置无边框
menu.setWindowFlags(QtCore.Qt.FramelessWindowHint)
# 设置半透明背景
menu.setAttribute(QtCore.Qt.WA_TranslucentBackground)
- 方法2
在Pixmap上绘制一个圆角矩形作为QMenu的Mask
C++ Qt的代码如下
QPixmap px(this->size()); //Create pixmap with the same size of current widget
px.fill(Qt::transparent); //Fill transparent
QPainter p(&px);
QBrush brush;
brush.setStyle(Qt::SolidPattern); //For fill
p.setBrush(brush);
p.drawRoundedRect(this->rect(), 15.0, 15.0); //Draw filled rounded rectangle on pixmap
this->setMask(px.mask()); //The the mask for current widget.