用于截图放大等
import sys
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow
from PySide6.QtGui import QPixmap, QPainter, QPen, QColor
from PySide6.QtCore import Qt, QRect, QPoint
class 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 = False
self.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 += width
width = abs(width)
if height < 0:
y += height
height = 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())