pyqt5利用qtgui显示图片在label标签 且图片比例大小不改变
时间: 2023-05-31 09:06:21 浏览: 66
在PyQt5中,可以使用QPixmap和QLabel组合来显示图片,并且可以保持图片比例大小不变。下面是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
from PyQt5.QtGui import QPixmap
class ImageWidget(QWidget):
def __init__(self, image_path):
super().__init__()
self.label = QLabel(self)
self.pixmap = QPixmap(image_path)
self.label.setPixmap(self.pixmap)
self.label.setScaledContents(True)
self.setGeometry(100, 100, self.pixmap.width(), self.pixmap.height())
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
image_widget = ImageWidget('image.jpg')
image_widget.show()
sys.exit(app.exec_())
```
在上面的示例中,我们创建了一个名为`ImageWidget`的自定义QWidget,它包含一个QLabel和QPixmap。我们使用`setPixmap()`方法设置标签的图像,然后使用`setScaledContents(True)`方法将图像比例大小自动缩放到标签大小。
最后,我们使用`setGeometry()`方法将QWidget的大小设置为图像大小。
运行示例代码,将会显示名为`image.jpg`的图像,且图像比例大小不会改变。