canvas.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. from qtpy import QtCore
  2. from qtpy import QtGui
  3. from qtpy import QtWidgets
  4. from labelme import QT5
  5. from labelme.shape import Shape
  6. import labelme.utils
  7. # TODO(unknown):
  8. # - [maybe] Find optimal epsilon value.
  9. CURSOR_DEFAULT = QtCore.Qt.ArrowCursor
  10. CURSOR_POINT = QtCore.Qt.PointingHandCursor
  11. CURSOR_DRAW = QtCore.Qt.CrossCursor
  12. CURSOR_MOVE = QtCore.Qt.ClosedHandCursor
  13. CURSOR_GRAB = QtCore.Qt.OpenHandCursor
  14. class Canvas(QtWidgets.QWidget):
  15. zoomRequest = QtCore.Signal(int, QtCore.QPoint)
  16. scrollRequest = QtCore.Signal(int, int)
  17. newShape = QtCore.Signal()
  18. selectionChanged = QtCore.Signal(bool)
  19. shapeMoved = QtCore.Signal()
  20. drawingPolygon = QtCore.Signal(bool)
  21. edgeSelected = QtCore.Signal(bool)
  22. CREATE, EDIT = 0, 1
  23. # polygon, rectangle, line, or point
  24. _createMode = 'polygon'
  25. _fill_drawing = False
  26. def __init__(self, *args, **kwargs):
  27. self.epsilon = kwargs.pop('epsilon', 10.0)
  28. super(Canvas, self).__init__(*args, **kwargs)
  29. # Initialise local state.
  30. self.mode = self.EDIT
  31. self.shapes = []
  32. self.shapesBackups = []
  33. self.current = None
  34. self.selectedShape = None # save the selected shape here
  35. self.selectedShapeCopy = None
  36. self.lineColor = QtGui.QColor(0, 0, 255)
  37. # self.line represents:
  38. # - createMode == 'polygon': edge from last point to current
  39. # - createMode == 'rectangle': diagonal line of the rectangle
  40. # - createMode == 'line': the line
  41. # - createMode == 'point': the point
  42. self.line = Shape(line_color=self.lineColor)
  43. self.prevPoint = QtCore.QPoint()
  44. self.prevMovePoint = QtCore.QPoint()
  45. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  46. self.scale = 1.0
  47. self.pixmap = QtGui.QPixmap()
  48. self.visible = {}
  49. self._hideBackround = False
  50. self.hideBackround = False
  51. self.hShape = None
  52. self.hVertex = None
  53. self.hEdge = None
  54. self.movingShape = False
  55. self._painter = QtGui.QPainter()
  56. self._cursor = CURSOR_DEFAULT
  57. # Menus:
  58. self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
  59. # Set widget options.
  60. self.setMouseTracking(True)
  61. self.setFocusPolicy(QtCore.Qt.WheelFocus)
  62. def fillDrawing(self):
  63. return self._fill_drawing
  64. def setFillDrawing(self, value):
  65. self._fill_drawing = value
  66. @property
  67. def createMode(self):
  68. return self._createMode
  69. @createMode.setter
  70. def createMode(self, value):
  71. if value not in ['polygon', 'rectangle', 'circle',
  72. 'line', 'point', 'linestrip']:
  73. raise ValueError('Unsupported createMode: %s' % value)
  74. self._createMode = value
  75. def storeShapes(self):
  76. shapesBackup = []
  77. for shape in self.shapes:
  78. shapesBackup.append(shape.copy())
  79. if len(self.shapesBackups) >= 10:
  80. self.shapesBackups = self.shapesBackups[-9:]
  81. self.shapesBackups.append(shapesBackup)
  82. @property
  83. def isShapeRestorable(self):
  84. if len(self.shapesBackups) < 2:
  85. return False
  86. return True
  87. def restoreShape(self):
  88. if not self.isShapeRestorable:
  89. return
  90. self.shapesBackups.pop() # latest
  91. shapesBackup = self.shapesBackups.pop()
  92. self.shapes = shapesBackup
  93. self.repaint()
  94. def enterEvent(self, ev):
  95. self.overrideCursor(self._cursor)
  96. def leaveEvent(self, ev):
  97. self.restoreCursor()
  98. def focusOutEvent(self, ev):
  99. self.restoreCursor()
  100. def isVisible(self, shape):
  101. return self.visible.get(shape, True)
  102. def drawing(self):
  103. return self.mode == self.CREATE
  104. def editing(self):
  105. return self.mode == self.EDIT
  106. def setEditing(self, value=True):
  107. self.mode = self.EDIT if value else self.CREATE
  108. if not value: # Create
  109. self.unHighlight()
  110. self.deSelectShape()
  111. def unHighlight(self):
  112. if self.hShape:
  113. self.hShape.highlightClear()
  114. self.hVertex = self.hShape = None
  115. def selectedVertex(self):
  116. return self.hVertex is not None
  117. def mouseMoveEvent(self, ev):
  118. """Update line with last point and current coordinates."""
  119. try:
  120. if QT5:
  121. pos = self.transformPos(ev.localPos())
  122. else:
  123. pos = self.transformPos(ev.posF())
  124. except AttributeError:
  125. return
  126. self.prevMovePoint = pos
  127. self.restoreCursor()
  128. # Polygon drawing.
  129. if self.drawing():
  130. self.line.shape_type = self.createMode
  131. self.overrideCursor(CURSOR_DRAW)
  132. if not self.current:
  133. return
  134. color = self.lineColor
  135. if self.outOfPixmap(pos):
  136. # Don't allow the user to draw outside the pixmap.
  137. # Project the point to the pixmap's edges.
  138. pos = self.intersectionPoint(self.current[-1], pos)
  139. elif len(self.current) > 1 and self.createMode == 'polygon' and\
  140. self.closeEnough(pos, self.current[0]):
  141. # Attract line to starting point and
  142. # colorise to alert the user.
  143. pos = self.current[0]
  144. color = self.current.line_color
  145. self.overrideCursor(CURSOR_POINT)
  146. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  147. if self.createMode in ['polygon', 'linestrip']:
  148. self.line[0] = self.current[-1]
  149. self.line[1] = pos
  150. elif self.createMode == 'rectangle':
  151. self.line.points = [self.current[0], pos]
  152. self.line.close()
  153. elif self.createMode == 'circle':
  154. self.line.points = [self.current[0], pos]
  155. self.line.shape_type = "circle"
  156. elif self.createMode == 'line':
  157. self.line.points = [self.current[0], pos]
  158. self.line.close()
  159. elif self.createMode == 'point':
  160. self.line.points = [self.current[0]]
  161. self.line.close()
  162. self.line.line_color = color
  163. self.repaint()
  164. self.current.highlightClear()
  165. return
  166. # Polygon copy moving.
  167. if QtCore.Qt.RightButton & ev.buttons():
  168. if self.selectedShapeCopy and self.prevPoint:
  169. self.overrideCursor(CURSOR_MOVE)
  170. self.boundedMoveShape(self.selectedShapeCopy, pos)
  171. self.repaint()
  172. elif self.selectedShape:
  173. self.selectedShapeCopy = self.selectedShape.copy()
  174. self.repaint()
  175. return
  176. # Polygon/Vertex moving.
  177. self.movingShape = False
  178. if QtCore.Qt.LeftButton & ev.buttons():
  179. if self.selectedVertex():
  180. self.boundedMoveVertex(pos)
  181. self.repaint()
  182. self.movingShape = True
  183. elif self.selectedShape and self.prevPoint:
  184. self.overrideCursor(CURSOR_MOVE)
  185. self.boundedMoveShape(self.selectedShape, pos)
  186. self.repaint()
  187. self.movingShape = True
  188. return
  189. # Just hovering over the canvas, 2 posibilities:
  190. # - Highlight shapes
  191. # - Highlight vertex
  192. # Update shape/vertex fill and tooltip value accordingly.
  193. self.setToolTip("Image")
  194. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  195. # Look for a nearby vertex to highlight. If that fails,
  196. # check if we happen to be inside a shape.
  197. index = shape.nearestVertex(pos, self.epsilon / self.scale)
  198. index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
  199. if index is not None:
  200. if self.selectedVertex():
  201. self.hShape.highlightClear()
  202. self.hVertex = index
  203. self.hShape = shape
  204. self.hEdge = index_edge
  205. shape.highlightVertex(index, shape.MOVE_VERTEX)
  206. self.overrideCursor(CURSOR_POINT)
  207. self.setToolTip("Click & drag to move point")
  208. self.setStatusTip(self.toolTip())
  209. self.update()
  210. break
  211. elif shape.containsPoint(pos):
  212. if self.selectedVertex():
  213. self.hShape.highlightClear()
  214. self.hVertex = None
  215. self.hShape = shape
  216. self.hEdge = index_edge
  217. self.setToolTip(
  218. "Click & drag to move shape '%s'" % shape.label)
  219. self.setStatusTip(self.toolTip())
  220. self.overrideCursor(CURSOR_GRAB)
  221. self.update()
  222. break
  223. else: # Nothing found, clear highlights, reset state.
  224. if self.hShape:
  225. self.hShape.highlightClear()
  226. self.update()
  227. self.hVertex, self.hShape, self.hEdge = None, None, None
  228. self.edgeSelected.emit(self.hEdge is not None)
  229. def addPointToEdge(self):
  230. if (self.hShape is None and
  231. self.hEdge is None and
  232. self.prevMovePoint is None):
  233. return
  234. shape = self.hShape
  235. index = self.hEdge
  236. point = self.prevMovePoint
  237. shape.insertPoint(index, point)
  238. shape.highlightVertex(index, shape.MOVE_VERTEX)
  239. self.hShape = shape
  240. self.hVertex = index
  241. self.hEdge = None
  242. def mousePressEvent(self, ev):
  243. if QT5:
  244. pos = self.transformPos(ev.localPos())
  245. else:
  246. pos = self.transformPos(ev.posF())
  247. if ev.button() == QtCore.Qt.LeftButton:
  248. if self.drawing():
  249. if self.current:
  250. # Add point to existing shape.
  251. if self.createMode == 'polygon':
  252. self.current.addPoint(self.line[1])
  253. self.line[0] = self.current[-1]
  254. if self.current.isClosed():
  255. self.finalise()
  256. elif self.createMode in ['rectangle', 'circle', 'line']:
  257. assert len(self.current.points) == 1
  258. self.current.points = self.line.points
  259. self.finalise()
  260. elif self.createMode == 'linestrip':
  261. self.current.addPoint(self.line[1])
  262. self.line[0] = self.current[-1]
  263. if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
  264. self.finalise()
  265. elif not self.outOfPixmap(pos):
  266. # Create new shape.
  267. self.current = Shape(shape_type=self.createMode)
  268. self.current.addPoint(pos)
  269. if self.createMode == 'point':
  270. self.finalise()
  271. else:
  272. if self.createMode == 'circle':
  273. self.current.shape_type = 'circle'
  274. self.line.points = [pos, pos]
  275. self.setHiding()
  276. self.drawingPolygon.emit(True)
  277. self.update()
  278. else:
  279. self.selectShapePoint(pos)
  280. self.prevPoint = pos
  281. self.repaint()
  282. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  283. self.selectShapePoint(pos)
  284. self.prevPoint = pos
  285. self.repaint()
  286. def mouseReleaseEvent(self, ev):
  287. if ev.button() == QtCore.Qt.RightButton:
  288. menu = self.menus[bool(self.selectedShapeCopy)]
  289. self.restoreCursor()
  290. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  291. and self.selectedShapeCopy:
  292. # Cancel the move by deleting the shadow copy.
  293. self.selectedShapeCopy = None
  294. self.repaint()
  295. elif ev.button() == QtCore.Qt.LeftButton and self.selectedShape:
  296. self.overrideCursor(CURSOR_GRAB)
  297. if self.movingShape:
  298. self.storeShapes()
  299. self.shapeMoved.emit()
  300. def endMove(self, copy=False):
  301. assert self.selectedShape and self.selectedShapeCopy
  302. shape = self.selectedShapeCopy
  303. # del shape.fill_color
  304. # del shape.line_color
  305. if copy:
  306. self.shapes.append(shape)
  307. self.selectedShape.selected = False
  308. self.selectedShape = shape
  309. self.repaint()
  310. else:
  311. shape.label = self.selectedShape.label
  312. self.deleteSelected()
  313. self.shapes.append(shape)
  314. self.storeShapes()
  315. self.selectedShapeCopy = None
  316. def hideBackroundShapes(self, value):
  317. self.hideBackround = value
  318. if self.selectedShape:
  319. # Only hide other shapes if there is a current selection.
  320. # Otherwise the user will not be able to select a shape.
  321. self.setHiding(True)
  322. self.repaint()
  323. def setHiding(self, enable=True):
  324. self._hideBackround = self.hideBackround if enable else False
  325. def canCloseShape(self):
  326. return self.drawing() and self.current and len(self.current) > 2
  327. def mouseDoubleClickEvent(self, ev):
  328. # We need at least 4 points here, since the mousePress handler
  329. # adds an extra one before this handler is called.
  330. if self.canCloseShape() and len(self.current) > 3:
  331. self.current.popPoint()
  332. self.finalise()
  333. def selectShape(self, shape):
  334. self.deSelectShape()
  335. shape.selected = True
  336. self.selectedShape = shape
  337. self.setHiding()
  338. self.selectionChanged.emit(True)
  339. self.update()
  340. def selectShapePoint(self, point):
  341. """Select the first shape created which contains this point."""
  342. self.deSelectShape()
  343. if self.selectedVertex(): # A vertex is marked for selection.
  344. index, shape = self.hVertex, self.hShape
  345. shape.highlightVertex(index, shape.MOVE_VERTEX)
  346. return
  347. for shape in reversed(self.shapes):
  348. if self.isVisible(shape) and shape.containsPoint(point):
  349. shape.selected = True
  350. self.selectedShape = shape
  351. self.calculateOffsets(shape, point)
  352. self.setHiding()
  353. self.selectionChanged.emit(True)
  354. return
  355. def calculateOffsets(self, shape, point):
  356. rect = shape.boundingRect()
  357. x1 = rect.x() - point.x()
  358. y1 = rect.y() - point.y()
  359. x2 = (rect.x() + rect.width() - 1) - point.x()
  360. y2 = (rect.y() + rect.height() - 1) - point.y()
  361. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  362. def boundedMoveVertex(self, pos):
  363. index, shape = self.hVertex, self.hShape
  364. point = shape[index]
  365. if self.outOfPixmap(pos):
  366. pos = self.intersectionPoint(point, pos)
  367. shape.moveVertexBy(index, pos - point)
  368. def boundedMoveShape(self, shape, pos):
  369. if self.outOfPixmap(pos):
  370. return False # No need to move
  371. o1 = pos + self.offsets[0]
  372. if self.outOfPixmap(o1):
  373. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  374. o2 = pos + self.offsets[1]
  375. if self.outOfPixmap(o2):
  376. pos += QtCore.QPoint(min(0, self.pixmap.width() - o2.x()),
  377. min(0, self.pixmap.height() - o2.y()))
  378. # XXX: The next line tracks the new position of the cursor
  379. # relative to the shape, but also results in making it
  380. # a bit "shaky" when nearing the border and allows it to
  381. # go outside of the shape's area for some reason.
  382. # self.calculateOffsets(self.selectedShape, pos)
  383. dp = pos - self.prevPoint
  384. if dp:
  385. shape.moveBy(dp)
  386. self.prevPoint = pos
  387. return True
  388. return False
  389. def deSelectShape(self):
  390. if self.selectedShape:
  391. self.selectedShape.selected = False
  392. self.selectedShape = None
  393. self.setHiding(False)
  394. self.selectionChanged.emit(False)
  395. self.update()
  396. def deleteSelected(self):
  397. if self.selectedShape:
  398. shape = self.selectedShape
  399. self.shapes.remove(self.selectedShape)
  400. self.storeShapes()
  401. self.selectedShape = None
  402. self.update()
  403. return shape
  404. def copySelectedShape(self):
  405. if self.selectedShape:
  406. shape = self.selectedShape.copy()
  407. self.deSelectShape()
  408. self.shapes.append(shape)
  409. self.storeShapes()
  410. shape.selected = True
  411. self.selectedShape = shape
  412. self.boundedShiftShape(shape)
  413. return shape
  414. def boundedShiftShape(self, shape):
  415. # Try to move in one direction, and if it fails in another.
  416. # Give up if both fail.
  417. point = shape[0]
  418. offset = QtCore.QPoint(2.0, 2.0)
  419. self.calculateOffsets(shape, point)
  420. self.prevPoint = point
  421. if not self.boundedMoveShape(shape, point - offset):
  422. self.boundedMoveShape(shape, point + offset)
  423. def paintEvent(self, event):
  424. if not self.pixmap:
  425. return super(Canvas, self).paintEvent(event)
  426. p = self._painter
  427. p.begin(self)
  428. p.setRenderHint(QtGui.QPainter.Antialiasing)
  429. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  430. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  431. p.scale(self.scale, self.scale)
  432. p.translate(self.offsetToCenter())
  433. p.drawPixmap(0, 0, self.pixmap)
  434. Shape.scale = self.scale
  435. for shape in self.shapes:
  436. if (shape.selected or not self._hideBackround) and \
  437. self.isVisible(shape):
  438. shape.fill = shape.selected or shape == self.hShape
  439. shape.paint(p)
  440. if self.current:
  441. self.current.paint(p)
  442. self.line.paint(p)
  443. if self.selectedShapeCopy:
  444. self.selectedShapeCopy.paint(p)
  445. if (self.fillDrawing() and self.createMode == 'polygon' and
  446. self.current is not None and len(self.current.points) >= 2):
  447. drawing_shape = self.current.copy()
  448. drawing_shape.addPoint(self.line[1])
  449. drawing_shape.fill = True
  450. drawing_shape.fill_color.setAlpha(64)
  451. drawing_shape.paint(p)
  452. p.end()
  453. def transformPos(self, point):
  454. """Convert from widget-logical coordinates to painter-logical ones."""
  455. return point / self.scale - self.offsetToCenter()
  456. def offsetToCenter(self):
  457. s = self.scale
  458. area = super(Canvas, self).size()
  459. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  460. aw, ah = area.width(), area.height()
  461. x = (aw - w) / (2 * s) if aw > w else 0
  462. y = (ah - h) / (2 * s) if ah > h else 0
  463. return QtCore.QPoint(x, y)
  464. def outOfPixmap(self, p):
  465. w, h = self.pixmap.width(), self.pixmap.height()
  466. return not (0 <= p.x() < w and 0 <= p.y() < h)
  467. def finalise(self):
  468. assert self.current
  469. self.current.close()
  470. self.shapes.append(self.current)
  471. self.storeShapes()
  472. self.current = None
  473. self.setHiding(False)
  474. self.newShape.emit()
  475. self.update()
  476. def closeEnough(self, p1, p2):
  477. # d = distance(p1 - p2)
  478. # m = (p1-p2).manhattanLength()
  479. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  480. # divide by scale to allow more precision when zoomed in
  481. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  482. def intersectionPoint(self, p1, p2):
  483. # Cycle through each image edge in clockwise fashion,
  484. # and find the one intersecting the current line segment.
  485. # http://paulbourke.net/geometry/lineline2d/
  486. size = self.pixmap.size()
  487. points = [(0, 0),
  488. (size.width() - 1, 0),
  489. (size.width() - 1, size.height() - 1),
  490. (0, size.height() - 1)]
  491. x1, y1 = p1.x(), p1.y()
  492. x2, y2 = p2.x(), p2.y()
  493. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  494. x3, y3 = points[i]
  495. x4, y4 = points[(i + 1) % 4]
  496. if (x, y) == (x1, y1):
  497. # Handle cases where previous point is on one of the edges.
  498. if x3 == x4:
  499. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  500. else: # y3 == y4
  501. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  502. return QtCore.QPoint(x, y)
  503. def intersectingEdges(self, point1, point2, points):
  504. """Find intersecting edges.
  505. For each edge formed by `points', yield the intersection
  506. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  507. Also return the distance of `(x2,y2)' to the middle of the
  508. edge along with its index, so that the one closest can be chosen.
  509. """
  510. (x1, y1) = point1
  511. (x2, y2) = point2
  512. for i in range(4):
  513. x3, y3 = points[i]
  514. x4, y4 = points[(i + 1) % 4]
  515. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  516. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  517. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  518. if denom == 0:
  519. # This covers two cases:
  520. # nua == nub == 0: Coincident
  521. # otherwise: Parallel
  522. continue
  523. ua, ub = nua / denom, nub / denom
  524. if 0 <= ua <= 1 and 0 <= ub <= 1:
  525. x = x1 + ua * (x2 - x1)
  526. y = y1 + ua * (y2 - y1)
  527. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  528. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  529. yield d, i, (x, y)
  530. # These two, along with a call to adjustSize are required for the
  531. # scroll area.
  532. def sizeHint(self):
  533. return self.minimumSizeHint()
  534. def minimumSizeHint(self):
  535. if self.pixmap:
  536. return self.scale * self.pixmap.size()
  537. return super(Canvas, self).minimumSizeHint()
  538. def wheelEvent(self, ev):
  539. if QT5:
  540. mods = ev.modifiers()
  541. delta = ev.angleDelta()
  542. if QtCore.Qt.ControlModifier == int(mods):
  543. # with Ctrl/Command key
  544. # zoom
  545. self.zoomRequest.emit(delta.y(), ev.pos())
  546. else:
  547. # scroll
  548. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  549. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  550. else:
  551. if ev.orientation() == QtCore.Qt.Vertical:
  552. mods = ev.modifiers()
  553. if QtCore.Qt.ControlModifier == int(mods):
  554. # with Ctrl/Command key
  555. self.zoomRequest.emit(ev.delta(), ev.pos())
  556. else:
  557. self.scrollRequest.emit(
  558. ev.delta(),
  559. QtCore.Qt.Horizontal
  560. if (QtCore.Qt.ShiftModifier == int(mods))
  561. else QtCore.Qt.Vertical)
  562. else:
  563. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  564. ev.accept()
  565. def keyPressEvent(self, ev):
  566. key = ev.key()
  567. if key == QtCore.Qt.Key_Escape and self.current:
  568. self.current = None
  569. self.drawingPolygon.emit(False)
  570. self.update()
  571. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  572. self.finalise()
  573. def setLastLabel(self, text, flags):
  574. assert text
  575. self.shapes[-1].label = text
  576. self.shapes[-1].flags = flags
  577. self.shapesBackups.pop()
  578. self.storeShapes()
  579. return self.shapes[-1]
  580. def undoLastLine(self):
  581. assert self.shapes
  582. self.current = self.shapes.pop()
  583. self.current.setOpen()
  584. if self.createMode in ['polygon', 'linestrip']:
  585. self.line.points = [self.current[-1], self.current[0]]
  586. elif self.createMode in ['rectangle', 'line', 'circle']:
  587. self.current.points = self.current.points[0:1]
  588. elif self.createMode == 'point':
  589. self.current = None
  590. self.drawingPolygon.emit(True)
  591. def undoLastPoint(self):
  592. if not self.current or self.current.isClosed():
  593. return
  594. self.current.popPoint()
  595. if len(self.current) > 0:
  596. self.line[0] = self.current[-1]
  597. else:
  598. self.current = None
  599. self.drawingPolygon.emit(False)
  600. self.repaint()
  601. def loadPixmap(self, pixmap):
  602. self.pixmap = pixmap
  603. self.shapes = []
  604. self.repaint()
  605. def loadShapes(self, shapes, replace=True):
  606. if replace:
  607. self.shapes = list(shapes)
  608. else:
  609. self.shapes.extend(shapes)
  610. self.storeShapes()
  611. self.current = None
  612. self.repaint()
  613. def setShapeVisible(self, shape, value):
  614. self.visible[shape] = value
  615. self.repaint()
  616. def overrideCursor(self, cursor):
  617. self.restoreCursor()
  618. self._cursor = cursor
  619. QtWidgets.QApplication.setOverrideCursor(cursor)
  620. def restoreCursor(self):
  621. QtWidgets.QApplication.restoreOverrideCursor()
  622. def resetState(self):
  623. self.restoreCursor()
  624. self.pixmap = None
  625. self.shapesBackups = []
  626. self.update()