用于截图放大等
import sys
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow
from PySide6.QtGui import QPixmap, QPainter, QPen, QColor
from PySide6.QtCore import Qt, QRect, QPointclass ImageLabel(QLabel):def __init__(self, parent=None):super().__init__(parent)self.start_pos = QPoint() # 鼠标起点self.end_pos = QPoint() # 鼠标终点self.erase = False # 擦除self.rect = QRect() # 方框# 重新定义鼠标按下事件def mousePressEvent(self, event):if event.button() == Qt.LeftButton:self.start_pos = event.position().toPoint()self.erase = Falseself.rect = QRect()# 重新定义鼠标移动事件def mouseMoveEvent(self, event):if self.start_pos:self.end_pos = event.position().toPoint()self.rect = QRect(self.start_pos, self.end_pos)self.update()# 重新定义鼠标松开事件def mouseReleaseEvent(self, event):if event.button() == Qt.LeftButton:self.end_pos = event.position().toPoint()self.rect = QRect(self.start_pos, self.end_pos)self.erase = True # 这一行决定了松开鼠标后方框是否擦除self.update()self.normalize_rect()# print(self.rect.getRect())# 重新定义绘画事件def paintEvent(self, event):super().paintEvent(event)painter = QPainter(self)if not self.erase: # 不擦除painter.setPen(QPen(QColor(255, 0, 0, 255), 2, Qt.SolidLine))else: # 擦除painter.setPen(QPen(QColor(0, 0, 0, 0), 2, Qt.SolidLine))painter.drawRect(self.rect)# 将得到的方框所有参数都转换成正数def normalize_rect(self):x = self.rect.x()y = self.rect.y()width = self.rect.width()height = self.rect.height()if width < 0:x += widthwidth = abs(width)if height < 0:y += heightheight = abs(height)self.rect = QRect(x, y, width, height)print(self.rect)class MainWindow(QMainWindow):def __init__(self):super().__init__()self.image_label = ImageLabel()self.setCentralWidget(self.image_label)if __name__ == '__main__':app = QApplication(sys.argv)window = MainWindow()window.show()sys.exit(app.exec())