QtWidgets.QLabel创建圆形的lable
时间: 2024-05-06 22:19:04 浏览: 22
要创建一个圆形 QLabel,你可以通过使用QLabel的setStyleSheet方法来设置其样式表。以下是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtCore import Qt
class CircleLabel(QLabel):
def __init__(self, parent=None):
super(CircleLabel, self).__init__(parent)
self.setFixedSize(100, 100)
self.setScaledContents(True)
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(Qt.white)
painter.setPen(Qt.NoPen)
painter.drawEllipse(self.rect())
super(CircleLabel, self).paintEvent(event)
app = QApplication([])
widget = QWidget()
label = CircleLabel(widget)
label.setPixmap(QPixmap("image.png"))
label.setStyleSheet("background-color: transparent;")
widget.show()
app.exec_()
```
在这个例子中,我们创建了一个CircleLabel类,它继承自QLabel。我们在CircleLabel的构造函数中调用了setFixedSize方法,以确保标签具有固定的大小。然后,我们重写了paintEvent方法,以便在标签上绘制一个圆形背景。最后,我们在主代码中创建了一个CircleLabel实例,并将其添加到QWidget中。
为了使标签的背景透明,我们还使用了setStyleSheet方法,将其background-color样式设置为transparent。你可以将图片路径替换为你自己的图片路径,这样就可以在标签中显示图像了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)