自定义QWidget显示图片, 清空图片
时间: 2024-05-09 16:18:55 浏览: 8
以下是一个示例代码,可以自定义一个继承自QWidget的类,用于显示图片,并提供清空图片的功能:
```python
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout
class ImageWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.label = QLabel(self)
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.label)
def set_image(self, image_path):
pixmap = QPixmap(image_path)
self.label.setPixmap(pixmap)
def clear_image(self):
self.label.clear()
```
使用时,可以调用set_image方法设置要显示的图片,调用clear_image方法清空图片:
```python
image_widget = ImageWidget()
image_widget.set_image("image.png")
# ...
image_widget.clear_image()
```