PyQt5 使用 QLabel 实现对图片圆角或者圆形图片

PyQt5 使用 QLabel 实现对图片圆角或者圆形图片

本文圆角实现代码,是基于Qt处理图片:设置图片圆角样式,支持全圆角和部分圆角这篇文章将C++Python重写得到,感谢!!实现方法就是使用QPainterQPainterPath,将原QPixmap对象,先裁剪出一个圆角QPixmap对象并返回,最后通过QLabelsetPixmap方法设置新图像

1. 实现效果

原图:
image  image
运行效果:
image  image

2. 创建圆角图像的方法

把原QPixmap对象,先裁剪出一个圆角QPixmap对象并返回

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@ File        : test_QLabel_rounded_corners.py
@ Author      : yqbao
@ Version     : V1.0.0
@ Description : QLabel 中显示圆角效果的图片
"""
from typing import Union

from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPixmap, QPainter, QPainterPath

def create_rounded_pixmap(pixmap: QPixmap, radius: Union[int, float]) -> QPixmap:
    """带圆角的 QPixmap"""
    if pixmap.isNull():  # 不处理空数据或者错误数据
        return pixmap

    # 获取图片尺寸
    image_width = pixmap.width()
    image_height = pixmap.height()

    # 处理大尺寸的图片,保证图片显示区域完整
    new_pixmap = QPixmap(
        pixmap.scaled(image_width, image_width if image_height == 0 else image_height, Qt.IgnoreAspectRatio,
                      Qt.SmoothTransformation))
    dest_image = QPixmap(image_width, image_height)
    dest_image.fill(Qt.transparent)

    painter = QPainter(dest_image)
    painter.setRenderHint(QPainter.Antialiasing)  # 抗锯齿
    painter.setRenderHint(QPainter.SmoothPixmapTransform)  # 平滑处理
    # 裁圆角
    path = QPainterPath()
    rect = QRectF(0, 0, image_width, image_height)
    path.addRoundedRect(rect, radius, radius)
    painter.setClipPath(path)
    painter.drawPixmap(0, 0, image_width, image_height, new_pixmap)

    return dest_image

3. 使用举例

创建QWidget,并添加QLabel,查看运行效果

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@ File        : test_QLabel_rounded_corners.py
@ Author      : yqbao
@ Version     : V1.0.0
@ Description : QLabel 中显示圆角效果的图片
"""
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout,QWidget

class RoundedQLabel(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()

        label = QLabel()
        label.setScaledContents(True)  # 自适应大小

        pixmap = QPixmap(r'image\30.png')  # 替换为你的图像路径
        rounded_pixmap = create_rounded_pixmap(pixmap, 45)

        # 正方形图片,圆角半径设置为尺寸一半,则是圆
        # pixmap = QPixmap(r'image\29.png')  # 替换为你的图像路径
        # rounded_pixmap = create_rounded_pixmap(pixmap, pixmap.height() / 2)

        label.setPixmap(rounded_pixmap)
        label.setFixedSize(pixmap.width() // 2, pixmap.height() // 2)  # 固定 label 大小

        # 将 QLabel 添加到布局中
        layout.addWidget(label)
        self.setLayout(layout)


if __name__ == '__main__':
    app = QApplication([])
    window = RoundedQLabel()
    window.show()
    app.exec_()

Qt处理图片:设置图片圆角样式,支持全圆角和部分圆角
本文章的原文地址
GitHub主页

posted @ 2024-09-26 11:01  星尘的博客  阅读(34)  评论(0编辑  收藏  举报