PyQt5 url设置圆形图片
作者:互联网
因为要仿QQ聊天界面需要用到圆形图片来做头像
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap, QPainter, QBrush
import requests
import sys
class My_circle_image(QWidget):
"""
从本地文件或URL设置圆形图片
"""
def __init__(self, url: str, size: int, mode: str = "local", parent=None):
super().__init__(parent)
self.resize(size, size)
if mode == "local":
self.img = QPixmap(url)
else:
self.img = QPixmap()
img_data = requests.get(url).content
self.img.loadFromData(img_data)
self.img = self.img.scaled(
QSize(size, size), Qt.KeepAspectRatio, Qt.SmoothTransformation
)
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, True)
painter.setPen(Qt.NoPen)
painter.setBrush(QBrush(self.img))
painter.drawRoundedRect(self.rect(), self.width() / 2, self.height() / 2)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = QWidget()
widget = My_circle_image(
r"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.wxcha.com%2Ffile%2F201812%2F22%2F580277dd05.jpg&refer=http%3A%2F%2Fimg.wxcha.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630665493&t=5bb0a47c1b77c08442a79e8ab68248d7",
80,
"remote",
window,
)
window.show()
sys.exit(app.exec_())
结果:
标签:__,img,url,self,PyQt5,圆形,import,painter,size 来源: https://blog.csdn.net/m0_43457463/article/details/119390538