用pyqt写一个通过鼠标滚动放大缩小图片的代码
时间: 2023-05-24 22:03:39 浏览: 212
A:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
class ImageWidget(QWidget):
def __init__(self, image_path):
super().__init__()
# 设置窗口大小
self.setGeometry(100, 100, 500, 500)
# 创建标签对象
self.image_label = QLabel(self)
# 加载图片
self.image_pixmap = QPixmap(image_path)
# 设置图片标签大小和位置
self.image_label.setGeometry(0, 0, self.width(), self.height())
self.image_label.setPixmap(self.image_pixmap)
# 开启滚轮事件监听
self.setMouseTracking(True)
def wheelEvent(self, event):
# 获取当前图片大小
width = self.image_pixmap.width()
height = self.image_pixmap.height()
# 计算缩放比例
delta = event.angleDelta().y() / 120
scale = 1 + delta * 0.1
# 重新设置图片大小
new_width = int(width * scale)
new_height = int(height * scale)
self.image_pixmap = self.image_pixmap.scaled(new_width, new_height, Qt.KeepAspectRatio)
# 更新图片标签和窗口大小
self.image_label.setPixmap(self.image_pixmap)
self.resize(new_width, new_height)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = ImageWidget('image.jpg')
window.show()
sys.exit(app.exec_())
```
注:该程序实现了图片的放大和缩小功能,只需将 `image.jpg` 替换为你自己的图片路径即可。
阅读全文