canvas.py 25 KB

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