canvas.py 25 KB

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