pyqt上显示图片并可以进行放大缩小,画图
时间: 2023-10-25 08:25:42 浏览: 109
PyQt6鼠标标点示例程序 QLabel图片上获取鼠标坐标并显示红点
要在PyQt中显示图片并可以进行放大缩小,可以使用QLabel和QPixmap类。以下是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
class ImageViewer(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Image Viewer')
self.setGeometry(100, 100, 800, 600)
self.image_label = QLabel(self)
self.image_label.setAlignment(Qt.AlignCenter)
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.image_label)
self.image_path = 'image.jpg' # 图片路径
self.show_image()
def show_image(self):
pixmap = QPixmap(self.image_path)
self.image_label.setPixmap(pixmap)
def wheelEvent(self, event):
if event.angleDelta().y() > 0:
self.image_label.resize(self.image_label.width() * 1.1, self.image_label.height() * 1.1)
else:
self.image_label.resize(self.image_label.width() * 0.9, self.image_label.height() * 0.9)
if __name__ == '__main__':
app = QApplication([])
iv = ImageViewer()
iv.show()
app.exec_()
```
该示例代码创建了一个名为ImageViewer的QWidget窗口,其中包含一个QLabel标签,用于显示一张图片。该窗口还实现了wheelEvent方法,以便捕获鼠标滚轮事件并缩放图片。要在该窗口中绘制图形,可以使用QPainter类。以下是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap, QPainter, QPen
from PyQt5.QtCore import Qt, QPoint
class Drawing(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Drawing')
self.setGeometry(100, 100, 800, 600)
self.setMouseTracking(True)
self.image_label = QLabel(self)
self.image_label.setAlignment(Qt.AlignCenter)
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.image_label)
self.image_path = 'image.jpg' # 图片路径
self.show_image()
self.drawing = False
self.last_point = QPoint()
def show_image(self):
pixmap = QPixmap(self.image_path)
self.image_label.setPixmap(pixmap)
def paintEvent(self, event):
if self.drawing:
painter = QPainter(self)
painter.setPen(QPen(Qt.red, 3))
painter.drawLine(self.last_point, self.current_point)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = True
self.last_point = self.current_point = event.pos()
def mouseMoveEvent(self, event):
if self.drawing:
self.current_point = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = False
def wheelEvent(self, event):
if event.angleDelta().y() > 0:
self.image_label.resize(self.image_label.width() * 1.1, self.image_label.height() * 1.1)
else:
self.image_label.resize(self.image_label.width() * 0.9, self.image_label.height() * 0.9)
if __name__ == '__main__':
app = QApplication([])
dw = Drawing()
dw.show()
app.exec_()
```
该示例代码创建了一个名为Drawing的QWidget窗口,其中可以在图片上绘制线条。该窗口还实现了mousePressEvent、mouseMoveEvent和mouseReleaseEvent方法,以便捕获鼠标事件并绘制线条。要在该窗口中绘制其他形状,可以使用QPainter类的其他方法。
阅读全文