canvas.py 24 KB

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