方法
void QPainter::setClipPath(const QPainterPath &path, Qt::ClipOperation operation = Qt::ReplaceClip)
Enables clipping, and sets the clip path for the painter to the given path, with the clip operation.
圆角代码
QPainter p(this);
QPainterPath path;
path.addRoundedRect(this->rect(),40,40);
p.setClipPath(path);
完整源文件
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowFlags(Qt::FramelessWindowHint |Qt::WindowStaysOnTopHint|Qt::Tool);
setAttribute(Qt::WA_TranslucentBackground);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
QPainterPath path;
path.addRoundedRect(this->rect(),40,40);
p.setClipPath(path);
p.drawImage(this->rect(),QImage(":/test.jpg").scaled(this->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
}
效果
扩展:设置等比缩放,并设置边框颜色
void Widget::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
//主背景色
// p.setPen(Qt::white);
// p.setBrush(Qt::white);
// p.drawRect(this->rect());
QPainterPath path;
QSize s = this->size()-QSize(3,3);
QImage img = QImage(":/test.jpg").scaled(s,Qt::KeepAspectRatio,Qt::SmoothTransformation);
QRectF rect{(this->width()-img.width())/2.0,(this->height()-img.height())/2.0,img.width()*1.0f,img.height()*1.0f};
//边框颜色
//p.setPen(Qt::lightGray);
p.setPen(Qt::green);
p.drawRoundedRect(rect.adjusted(-1,-1,1,1),10,10);
//绘制圆角图片
path.addRoundedRect(rect,10,10);
p.setClipPath(path);
p.drawImage(rect,img);
}