PyQt如何修改SelectImageTool类paintEvent的QRect实现可拖拽可调大小选区
解决方案
你不需要引入其他类或者RubberBand方案,直接修改现有的SelectImageTool类即可实现两个需求,只需要新增少量状态判断逻辑即可。
实现思路
- 新增状态变量区分三种操作模式:新建选区、拖拽移动选区、拖拽边缘调整选区大小
- 新增边缘检测阈值(默认8像素),鼠标落在选区边缘阈值范围内时判定为调整大小操作
- 鼠标移动时根据当前操作模式更新选区坐标,同时限制选区不能超出图片显示区域
- 自动切换鼠标样式,提升操作感知:选区内部是移动光标、边缘是调整大小光标、外部是十字新建光标
修改后的完整SelectImageTool类代码
class SelectImageTool(QLabel): def __init__(self, mStrImageName, mFlScaleFactor): super().__init__() self.aStrImageName=mStrImageName self.aFlScaleFactor=mFlScaleFactor # 选区坐标存储 self.select_rect = QRect() # 操作状态 self.operation_mode = 0 # 0:新建 1:移动 2:调整大小 self.drag_offset = None # 移动时的鼠标偏移 self.resize_edge = None # 调整时选中的边缘/角:left/right/top/bottom/topLeft/topRight/bottomLeft/bottomRight self.edge_threshold = 8 # 边缘检测阈值,单位像素 self.blnMousePress = False def _get_edge_hit(self, pos): """判断鼠标点击位置落在选区的哪个边缘""" rect = self.select_rect if not rect.isValid(): return None # 检查四个角 if QRect(rect.left()-self.edge_threshold, rect.top()-self.edge_threshold, self.edge_threshold*2, self.edge_threshold*2).contains(pos): return 'topLeft' if QRect(rect.right()-self.edge_threshold, rect.top()-self.edge_threshold, self.edge_threshold*2, self.edge_threshold*2).contains(pos): return 'topRight' if QRect(rect.left()-self.edge_threshold, rect.bottom()-self.edge_threshold, self.edge_threshold*2, self.edge_threshold*2).contains(pos): return 'bottomLeft' if QRect(rect.right()-self.edge_threshold, rect.bottom()-self.edge_threshold, self.edge_threshold*2, self.edge_threshold*2).contains(pos): return 'bottomRight' # 检查四个边 if QRect(rect.left()-self.edge_threshold, rect.top(), self.edge_threshold*2, rect.height()).contains(pos): return 'left' if QRect(rect.right()-self.edge_threshold, rect.top(), self.edge_threshold*2, rect.height()).contains(pos): return 'right' if QRect(rect.left(), rect.top()-self.edge_threshold, rect.width(), self.edge_threshold*2).contains(pos): return 'top' if QRect(rect.left(), rect.bottom()-self.edge_threshold, rect.width(), self.edge_threshold*2).contains(pos): return 'bottom' # 检查内部 if rect.contains(pos): return 'inside' return None def _update_cursor(self, pos): """根据鼠标位置更新光标样式""" edge = self._get_edge_hit(pos) if edge in ['left', 'right']: self.setCursor(Qt.SizeHorCursor) elif edge in ['top', 'bottom']: self.setCursor(Qt.SizeVerCursor) elif edge in ['topLeft', 'bottomRight']: self.setCursor(Qt.SizeFDiagCursor) elif edge in ['topRight', 'bottomLeft']: self.setCursor(Qt.SizeBDiagCursor) elif edge == 'inside': self.setCursor(Qt.SizeAllCursor) else: self.setCursor(Qt.CrossCursor) def mousePressEvent(self, event): self.blnMousePress = True pos = event.pos() edge_hit = self._get_edge_hit(pos) if edge_hit == 'inside': self.operation_mode = 1 self.drag_offset = pos - self.select_rect.topLeft() elif edge_hit is not None: self.operation_mode = 2 self.resize_edge = edge_hit else: self.operation_mode = 0 self.select_rect.setTopLeft(pos) self.select_rect.setBottomRight(pos) def mouseMoveEvent(self, event): pos = event.pos() if not self.blnMousePress: self._update_cursor(pos) return if self.operation_mode == 0: # 新建选区 self.select_rect.setBottomRight(pos) elif self.operation_mode == 1: # 移动选区 new_top_left = pos - self.drag_offset # 限制移动范围不超出label边界 new_top_left.setX(max(0, min(new_top_left.x(), self.width() - self.select_rect.width()))) new_top_left.setY(max(0, min(new_top_left.y(), self.height() - self.select_rect.height()))) self.select_rect.moveTopLeft(new_top_left) elif self.operation_mode == 2: # 调整大小 rect = self.select_rect if self.resize_edge == 'left': rect.setLeft(max(0, min(pos.x(), rect.right() - 10))) elif self.resize_edge == 'right': rect.setRight(min(self.width(), max(pos.x(), rect.left() + 10))) elif self.resize_edge == 'top': rect.setTop(max(0, min(pos.y(), rect.bottom() - 10))) elif self.resize_edge == 'bottom': rect.setBottom(min(self.height(), max(pos.y(), rect.top() + 10))) elif self.resize_edge == 'topLeft': rect.setLeft(max(0, min(pos.x(), rect.right() - 10))) rect.setTop(max(0, min(pos.y(), rect.bottom() - 10))) elif self.resize_edge == 'topRight': rect.setRight(min(self.width(), max(pos.x(), rect.left() + 10))) rect.setTop(max(0, min(pos.y(), rect.bottom() - 10))) elif self.resize_edge == 'bottomLeft': rect.setLeft(max(0, min(pos.x(), rect.right() - 10))) rect.setBottom(min(self.height(), max(pos.y(), rect.top() + 10))) elif self.resize_edge == 'bottomRight': rect.setRight(min(self.width(), max(pos.x(), rect.left() + 10))) rect.setBottom(min(self.height(), max(pos.y(), rect.top() + 10))) self.select_rect = rect # 限制选区最小尺寸10x10 if self.select_rect.width() < 10: self.select_rect.setWidth(10) if self.select_rect.height() < 10: self.select_rect.setHeight(10) self.update() def mouseReleaseEvent(self, event): self.blnMousePress = False self.operation_mode = 0 self.drag_offset = None self.resize_edge = None def paintEvent(self, event): super().paintEvent(event) if self.select_rect.isValid() and self.select_rect.width() > 0 and self.select_rect.height() > 0: pntSelectionRectangle = QPainter(self) pntSelectionRectangle.setPen(QPen(Qt.red,4,Qt.DashLine)) pntSelectionRectangle.drawRect(self.select_rect.normalized()) def setSelectionEdge(self): # 适配新的select_rect坐标 norm_rect = self.select_rect.normalized() iScalePosX0 = self.scaleCoordinates(norm_rect.left()) iScalePosX1 = self.scaleCoordinates(norm_rect.right()) iScalePosY0 = self.scaleCoordinates(norm_rect.top()) iScalePosY1 = self.scaleCoordinates(norm_rect.bottom()) iLeft = iScalePosX0 iTop = iScalePosY0 iWidth = abs(iScalePosX1-iScalePosX0) iHeight = abs(iScalePosY1-iScalePosY0) iRight = iLeft+iWidth iBottom = iTop+iHeight print (str(iLeft) + " " + str(iTop) + " "+ str(iRight) + " " + str(iBottom)) return iLeft, iTop, iRight, iBottom def scaleCoordinates(self,mIntCoordinate): return round(self.aFlScaleFactor*mIntCoordinate) def cropImageSelection(self): iLeft, iTop, iRight, iBottom = self.setSelectionEdge() try: imgSourcePicture = Image.open(self.aStrImageName) tupSize = imgSourcePicture.size iLeft = self.checkCoordinateLimit(iLeft, 0) iTop = self.checkCoordinateLimit(iTop, 0) iRight = self.checkCoordinateLimit(iRight, tupSize[0]) iBottom = self.checkCoordinateLimit(iBottom, tupSize[1]) imgCropped = imgSourcePicture.crop((iLeft, iTop, iRight, iBottom)) imgCropped.save("cropped.jpg") except IOError: pass def checkCoordinateLimit(self,mIntCoord, mIntLimit): if mIntLimit==0: iCoord = mIntCoord if mIntCoord >=mIntLimit else mIntLimit else: iCoord = mIntCoord if mIntCoord <=mIntLimit else mIntLimit return iCoord
功能说明
替换原类后直接运行即可实现以下操作:
- 按住鼠标在空白区域拖拽:新建选区
- 鼠标放在选区内部按住拖拽:整体移动选区位置
- 鼠标放在选区边缘/四角按住拖拽:调整选区大小
- 选区不会超出图片显示边界,且最小尺寸限制为10*10避免不可见
你原有代码的其他部分无需任何修改即可正常使用。
内容的提问来源于stack exchange,提问作者Nunkij
相关产品推荐
相关产品推荐

