python鼠标拖动正方形roi大小
时间: 2024-09-18 09:05:18 浏览: 43
在Python中,你可以使用PyQt或wxPython等GUI库结合鼠标事件来实现鼠标拖动调整正方形ROI(Region of Interest)的大小。以下是一个使用PyQt的例子:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QCursor, QGraphicsScene, QGraphicsView
from PyQt5.QtCore import Qt, QRectF, pyqtSignal
class ROIEditor(QMainWindow):
roi_size_changed = pyqtSignal(int, int)
def __init__(self):
super().__init__()
self.label = QLabel()
self.scene = QGraphicsScene(self.label)
self.view = QGraphicsView(self.scene)
self.square = QGraphicsRectItem(QRectF(0, 0, 100, 100), self.scene)
self.square.setFlags(Qt.ItemIsMovable | Qt.ItemSendsScenePositionChanges)
self.square.setCursor(Qt.SizeAllCursor)
self.scene.addItem(self.square)
self.view.resize(300, 300)
self.setCentralWidget(self.view)
self.square.moved.connect(self.update_square_size)
self.square.sizeChanged.connect(self.roi_size_changed.emit)
def update_square_size(self, new_pos):
pos = self.square.mapToScene(new_pos)
width, height = pos.width(), pos.height()
self.roi_size_changed.emit(width, height)
app = QApplication([])
editor = ROIEditor()
editor.show()
# 当ROI大小改变时,这里可以接收信号并做相应的处理
@appSlot(int, int)
def on_roi_size_change(width, height):
print(f"ROI size changed to {width}x{height}")
app.exec_()
```
在这个例子中,用户通过鼠标拖动正方形边角可以调整ROI的大小,当大小变化时会触发`roi_size_changed`信号,外部可以监听这个信号并处理。
阅读全文