def paint(self, painter, option, index): painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) model = index.model() view = self.parent() if view.hasFocus() and option.state & QStyle.State_MouseOver: painter.setPen(Qt.NoPen) painter.setBrush(Qt.gray) painter.drawRoundedRect(option.rect.adjusted(1, 1, -1, -1), self._ICON_MARGIN, self._ICON_MARGIN) pixmap = model.data(index, Qt.DecorationRole).pixmap(view.iconSize()) pm_rect = QRect( option.rect.topLeft() + QPoint(self._ICON_MARGIN + 1, self._ICON_MARGIN + 1), view.iconSize() - QSize(self._ICON_MARGIN * 2, self._ICON_MARGIN * 2)) painter.drawPixmap(pm_rect, pixmap) if option.state & QStyle.State_Selected: painter.setPen( QPen(Qt.red, 1.0, Qt.SolidLine, Qt.SquareCap, Qt.RoundJoin)) painter.setBrush(Qt.NoBrush) painter.drawRect(option.rect.adjusted(2, 2, -2, -2)) font = view.font() fm = QFontMetrics(font) text = os.path.splitext( os.path.basename(model.data(index, Qt.DisplayRole)))[0] text = fm.elidedText(text, Qt.ElideRight, view.iconSize().width() - 4) text_opt = QTextOption() text_opt.setAlignment(Qt.AlignHCenter) txt_rect = QRectF(QPointF(pm_rect.bottomLeft() + QPoint(0, 1)), QPointF(option.rect.bottomRight() - QPoint(4, 3))) painter.save() painter.setPen(Qt.NoPen) painter.setBrush(QColor(22, 22, 22, 220)) painter.drawRoundedRect(txt_rect.adjusted(-2, -2, 2, 2), 2, 2) painter.restore() painter.setPen(self.parent().palette().color(QPalette.WindowText)) painter.drawText(txt_rect, text, text_opt) font.setPointSize(8) fm = QFontMetrics(font) item = model.itemFromIndex(index) size_text = '%d x %d' % (item.size.width(), item.size.height()) size_rect = fm.boundingRect(option.rect, Qt.AlignLeft | Qt.AlignTop, size_text) size_rect.translate(4, 4) painter.save() painter.setPen(Qt.NoPen) painter.setBrush(QColor(22, 22, 22, 220)) painter.drawRoundedRect(size_rect.adjusted(-2, -2, 2, 2), 2, 2) painter.restore() painter.setFont(font) painter.drawText(size_rect, size_text)
def quad_to(path, cmd, data): new1st_pos = QPointF(data[0], data[1]) new_end_pos = QPointF(data[2], data[3]) path.quadTo(new1st_pos, new_end_pos) if cmd.islower(): current_pos = path.currentPosition() new1st_pos += current_pos new_end_pos += current_pos path.quadTo(new1st_pos, new_end_pos)
def cubic_to(path, cmd, data): new1st_pos = QPointF(data[0], data[1]) new2st_pos = QPointF(data[2], data[3]) new_end_pos = QPointF(data[4], data[5]) if cmd.islower(): current_pos = path.currentPosition() new1st_pos += current_pos new2st_pos += current_pos new_end_pos += current_pos path.cubicTo(new1st_pos, new2st_pos, new_end_pos)
def paint(self, painter, option, widget=None): path = QPainterPath() path.addRoundedRect(self.m_rect, 5, 5) anchor = self.mapFromParent(self.m_chart.mapToPosition(self.m_anchor)) if not self.m_rect.contains(anchor): point1 = QPointF() point2 = QPointF() # establish the position of the anchor point in relation to m_rect above = anchor.y() <= self.m_rect.top() aboveCenter = (anchor.y() > self.m_rect.top() and anchor.y() <= self.m_rect.center().y()) belowCenter = (anchor.y() > self.m_rect.center().y() and anchor.y() <= self.m_rect.bottom()) below = anchor.y() > self.m_rect.bottom() onLeft = anchor.x() <= self.m_rect.left() leftOfCenter = (anchor.x() > self.m_rect.left() and anchor.x() <= self.m_rect.center().x()) rightOfCenter = (anchor.x() > self.m_rect.center().x() and anchor.x() <= self.m_rect.right()) onRight = anchor.x() > self.m_rect.right() # get the nearest m_rect corner. x = (onRight + rightOfCenter) * self.m_rect.width() y = (below + belowCenter) * self.m_rect.height() cornerCase = ((above and onLeft) or (above and onRight) or (below and onLeft) or (below and onRight)) vertical = abs(anchor.x() - x) > abs(anchor.y() - y) x1 = (x + leftOfCenter * 10 - rightOfCenter * 20 + cornerCase * int(not vertical) * (onLeft * 10 - onRight * 20)) y1 = (y + aboveCenter * 10 - belowCenter * 20 + cornerCase * int(vertical) * (above * 10 - below * 20)) point1.setX(x1) point1.setY(y1) x2 = (x + leftOfCenter * 20 - rightOfCenter * 10 + cornerCase * int(not vertical) * (onLeft * 20 - onRight * 10)) y2 = (y + aboveCenter * 20 - belowCenter * 10 + cornerCase * int(vertical) * (above * 20 - below * 10)) point2.setX(x2) point2.setY(y2) path.moveTo(point1) path.lineTo(anchor) path.lineTo(point2) path = path.simplified() painter.setBrush(QColor(255, 255, 255)) painter.drawPath(path) painter.drawText(self.m_textRect, self.m_text)
def smooth_quad_to(path, cmd, data): elem_count = path.elementCount() prev_end_x, prevEndY = path.elementAt(elem_count - 1).x, path.elementAt(elem_count - 1).y prev1st_x, prev1stY = path.elementAt(elem_count - 2).x, path.elementAt(elem_count - 2).y new1st_pos = QPointF(2 * prev_end_x - prev1st_x, 2 * prevEndY - prev1stY) new_end_pos = QPointF(data[0], data[1]) if cmd.islower(): current_pos = path.currentPosition() new_end_pos += current_pos path.quadTo(new1st_pos, new_end_pos)
def pan(self, delta: QPoint) -> None: dx = QPointF(delta) / float(tdim) center = tileForCoordinate(self.latitude, self.longitude, self.zoom) - dx self.latitude = latitudeFromTile(center.y(), self.zoom) self.longitude = longitudeFromTile(center.x(), self.zoom) self.invalidate()
def get_points(self): points = list() for obj in self._point_objects: point = QPointF(obj.pos().x() + 5, obj.pos().y() + 5) points.append(point) return points
def tileForCoordinate(lat: float, lng: float, zoom: int) -> QPointF: radianLat = math.radians(lat) zn = float(1 << zoom) tx = (lng + 180.0) / 360.0 ty = 0.5 - math.log(math.tan(radianLat) + 1.0 / math.cos(radianLat)) / math.pi / 2.0 return QPointF(tx * zn, ty * zn)
def __init__(self, parent=None): self._base_size = 300 self._bezier_dict = { 'bezier': [ QPoint(0, 0), QPoint(75, 0), QPoint(225, 300), QPoint(300, 300)], 'linear': [ QPointF(0.000000, 0.000000), QPointF(75.000000, 75.000000), QPointF(225.000000, 225.000000), QPointF(300.000000, 300.000000)] } super(FallofCurveWidget, self).__init__(parent=parent) self.setObjectName('Falloff Curve') self.show() self.refresh()
def set_x(self, x): self._x = self.constraint(x, -1.0, 1.0) radius = (self._bounds.width() - self._knop_bounds.width()) * 0.5 self._knop_bounds.moveCenter( QPointF(self._bounds.center().x() + self._x * radius, self._knop_bounds.center().y())) self.update() self.xChanged.emit(self._x)
def set_y(self, y): self._y = self.constraint(y, -1.0, 1.0) radius = (self._bounds.width() - self._knop_bounds.width()) * 0.5 self._knop_bounds.moveCenter( QPointF(self._knop_bounds.center().x(), self._bounds.center().y() - self._y * radius)) self.update() self.yChanged.emit(self._x)
def calculate_start_angle(x1, y1, rx, ry, coordAngle, largeArcFlag, sweep_flag, x2, y2): def dotproduct(v1, v2): return sum((a * b for a, b in zip(v1, v2))) def length(v): return math.sqrt(dotproduct(v, v)) def angle(v1, v2): return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2))) rotated_x1 = math.cos(math.radians(coordAngle)) * ( (x1 - x2) / 2) + math.sin(math.radians(coordAngle)) * ((y1 - y2) / 2) rotated_y1 = -math.sin(math.radians(coordAngle)) * ( (x1 - x2) / 2) + math.cos(math.radians(coordAngle)) * ((y1 - y2) / 2) delta = rotated_x1**2 / rx**2 + rotated_y1**2 / ry**2 if delta > 1: rx *= math.sqrt(delta) ry *= math.sqrt(delta) _a = (rx**2 * ry**2 - rx**2 * rotated_y1**2 - ry**2 * rotated_x1**2) _b = (rx**2 * rotated_y1**2 + ry**2 * rotated_x1**2) var = math.sqrt(_a / _b) if largeArcFlag == sweep_flag: var *= -1 ccx = var * (rx * rotated_y1 / ry) ccy = var * -(ry * rotated_x1 / rx) cx = math.cos(math.radians(coordAngle)) * ccx - math.sin( math.radians(coordAngle)) * ccy + (x1 + x2) / 2 cy = math.sin(math.radians(coordAngle)) * ccx + math.cos( math.radians(coordAngle)) * ccy + (y1 + y2) / 2 start_angle = math.degrees( angle([1, 0], [(rotated_x1 - ccx) / rx, (rotated_y1 - ccy) / ry])) start_angle_sign = 1 * (rotated_y1 - ccy) / ry - 0 * (rotated_x1 - ccx) / rx if start_angle_sign == 0: start_angle_sign = 1.0 start_angle_sign /= abs(start_angle_sign) start_angle *= start_angle_sign try: sweep_angle = math.degrees( angle([(rotated_x1 - ccx) / rx, (rotated_y1 - ccy) / ry], [(-rotated_x1 - ccx) / rx, (-rotated_y1 - ccy) / ry])) except ValueError: sweep_angle = 180.0 sweep_angle_sign = (rotated_x1 - ccx) / rx * (-rotated_y1 - ccy) / ry - \ (rotated_y1 - ccy) / ry * (-rotated_x1 - ccx) / rx if sweep_angle_sign == 0: sweep_angle_sign = 1.0 sweep_angle_sign /= abs(sweep_angle_sign) sweep_angle *= sweep_angle_sign if sweep_flag == 0 and sweep_angle > 0: sweep_angle -= 360 elif sweep_flag == 1 and sweep_angle < 0: sweep_angle += 360 rect = QRectF(0, 0, rx * 2, ry * 2) rect.moveCenter(QPointF(cx, cy)) return (start_angle, sweep_angle, rect)
def __init__(self, chart): super().__init__(chart) self.m_chart = chart self.m_text = "" self.m_textRect = QRectF() self.m_rect = QRectF() self.m_anchor = QPointF() self.m_font = QFont()
def _move_line_to_center(self, new_pos): if not self._line: return x_offset = self._rect.x() - self._rect.width() / 2 y_offset = self._rect.y() - self._rect.height() / 2 new_center_pos = QPointF(new_pos.x() - x_offset, new_pos.y() - y_offset) p1 = new_center_pos if self._is_point1 else self._line.line().p1() p2 = self._line.line().p2() if self._is_point1 else new_center_pos self._line.setLine(QLineF(p1, p2))
def drawBackground(self, painter, rect): """ Override draw background method to write out image as background """ painter.setRenderHint(QPainter.Antialiasing) painter.fillRect(rect, self._color) painter.setPen(QPen(Qt.black, 0.5, Qt.DashLine)) painter.setBrush(QColor(67, 255, 163)) if self._use_bg_image and not self._pixmap.isNull(): painter.drawPixmap(QPointF(0, 0), self._pixmap)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.HighQualityAntialiasing) gradient = QRadialGradient(self._bounds.center(), self._bounds.width() * 0.5, self._bounds.center()) gradient.setFocalRadius(self._bounds.width() * 0.3) gradient.setCenterRadius(self._bounds.width() * 0.7) gradient.setColorAt(0, Qt.white) gradient.setColorAt(1, Qt.lightGray) painter.setPen(QPen(QBrush(Qt.gray), self._bounds.width() * 0.005)) painter.setBrush(QBrush(gradient)) painter.drawEllipse(self._bounds) painter.setPen(QPen(QBrush(Qt.gray), self._bounds.width() * 0.005)) painter.drawLine( QPointF(self._bounds.left(), self._bounds.center().y()), QPointF(self._bounds.center().x() - self._bounds.width() * 0.35, self._bounds.center().y())) painter.drawLine( QPointF(self._bounds.center().x() + self._bounds.width() * 0.35, self._bounds.center().y()), QPointF(self._bounds.right(), self._bounds.center().y())) painter.drawLine( QPointF(self._bounds.center().x(), self._bounds.top()), QPointF(self._bounds.center().x(), self._bounds.center().y() - self._bounds.width() * 0.35)) painter.drawLine( QPointF(self._bounds.center().x(), self._bounds.center().y() + self._bounds.width() * 0.35), QPointF(self._bounds.center().x(), self._bounds.bottom())) if not self.isEnabled(): return gradient = QRadialGradient(self._knop_bounds.center(), self._knop_bounds.width() * 0.5, self._knop_bounds.center()) gradient.setFocalRadius(self._knop_bounds.width() * 0.2) gradient.setCenterRadius(self._knop_bounds.width() * 0.5) gradient.setColorAt(0, Qt.gray) gradient.setColorAt(1, Qt.darkGray) painter.setPen(QPen(QBrush(Qt.darkGray), self._bounds.width() * 0.005)) painter.setBrush(QBrush(gradient)) painter.drawEllipse(self._knop_bounds)
def __init__(self, items, images, parent=None): super().__init__(parent) self.informationWindows = [] self.itemTable = QSqlRelationalTableModel(self) self.itemTable.setTable(items) self.itemTable.setRelation(1, QSqlRelation(images, "itemid", "file")) self.itemTable.select() self.scene = QGraphicsScene(self) self.scene.setSceneRect(0, 0, 465, 365) self.setScene(self.scene) self.addItems() self.setMinimumSize(470, 370) self.setMaximumSize(470, 370) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 370)) gradient.setColorAt(0, QColor("#868482")) gradient.setColorAt(1, QColor("#5d5b59")) self.setBackgroundBrush(gradient)
def create_ellipse_path(data): path = QPainterPath() path.addEllipse(QPointF(data.get('cx'), data.get('cy')), data.get('rx'), data.get('ry')) if 'transform' in data: m = re.match('^matrix\\((.+)\\)$', data.get('transform')) if m: args = map(lambda x: float(x), m.group(1).split()) if len(args) == 6: transform = QTransform(*args) path *= transform return path
def mouseMoveEvent(self, event): super(CurveNodeItem, self).mouseMoveEvent(event) curve_offset = -self.WIDTH * 0.5 scale_x = min(max(event.scenePos().x(), curve_offset), self.scene().base_size + curve_offset) scale_y = min(max(event.scenePos().y(), curve_offset), self.scene().base_size + curve_offset) if self._lock_x_pos: scale_x = self._lock_x_pos if self._snap is not False: scale_x = round((float(scale_x) / self._snap)) * self._snap scale_y = round((float(scale_y) / self._snap)) * self._snap self._new_pos = QPointF(scale_x, scale_y) self.setPos(self._new_pos) self.scene().update_curve() self.signals.curveUpdated.emit()
def mouseMoveEvent(self, event): delta_x = event.pos().x() - self._real_start_drag_pos.x() delta_y = event.pos().y() - self._real_start_drag_pos.y() new_pos = QPointF() if event.modifiers() in [Qt.ControlModifier, Qt.ShiftModifier, Qt.ControlModifier | Qt.ShiftModifier]: if event.modifiers() == Qt.ControlModifier: new_pos.setX(self.startDragpos.x() + delta_x / 2) new_pos.setY(self.startDragpos.y() + delta_y / 2) elif event.modifiers() == Qt.ShiftModifier: new_pos.setX(self.startDragpos.x() + delta_x / 4) new_pos.setY(self.startDragpos.y() + delta_y / 4) elif event.modifiers() == Qt.ControlModifier | Qt.ShiftModifier: new_pos.setX(self.startDragpos.x() + delta_x / 8) new_pos.setY(self.startDragpos.y() + delta_y / 8) mouse_event = QMouseEvent(event.type(), new_pos, event.button(), event.buttons(), event.modifiers()) super(Slider, self).mouseMoveEvent(mouse_event) self.setValue(self.value() - self._delta_value) else: super(Slider, self).mouseMoveEvent(event)
def printDocument(self, printer): loop = QEventLoop() result = False def printPreview(success): nonlocal result result = success loop.quit() self.m_page.print(printer, printPreview) loop.exec_() if not result: painter = QPainter() if painter.begin(printer): font = painter.font() font.setPixelSize(20) painter.setFont(font) painter.drawText(QPointF(10, 25), "Could not generate print preview.") painter.end()
def __init__(self, collapsed=False, parent=None): super(ExpandableArrow, self).__init__(parent=parent) self.setMaximumSize(24, 24) self.setMinimumWidth(24) self._arrow = None # Define vertical and horizontal arrow to avoid the deletion of its items during garbage collection # (this gc produces errors when trying to paint the arrow if we do not save them in a local variable self._arrow = None self._vertical = QPolygonF([QPointF(8.0, 7.0), QPointF(13.0, 12.0), QPointF(8.0, 17.0)]) self._horizontal = QPolygonF([QPointF(7.0, 8.0), QPointF(17.0, 8.0), QPointF(12.0, 13.0)]) self.setArrow(bool(collapsed))
def mousePressEvent(self, event): self._prev_value = self.value() self._start_drag_pos = event.pos() if event.button() == Qt.MidButton: if not self._draggers: self._draggers = SliderDraggers(parent=self, is_float=self._is_float, dragger_steps=self._dragger_steps) self._draggers.increment.connect(self.valueIncremented.emit) self._draggers.show() if self._is_float: self._draggers.move( self.mapToGlobal(QPoint(event.pos().x() - 1, event.pos().y() - self._draggers.height() / 2))) else: draggers_height = self._draggers.height() self._draggers.move( self.mapToGlobal( QPoint(event.pos().x() - 1, event.pos().y() - (self._draggers.height() - draggers_height / 6)))) elif event.button() == self._left_button and event.modifiers() not in \ [Qt.ControlModifier, Qt.ShiftModifier, Qt.ControlModifier | Qt.ShiftModifier]: buttons = Qt.MouseButtons(self._mid_button) mouse_event = QMouseEvent(event.type(), event.pos(), self._mid_button, buttons, event.modifiers()) super(Slider, self).mousePressEvent(mouse_event) elif event.modifiers() in [Qt.ControlModifier, Qt.ShiftModifier, Qt.ControlModifier | Qt.ShiftModifier]: style_slider = QStyleOptionSlider() style_slider.initFrom(self) style_slider.orientation = self.orientation() available = self.style().pixelMetric(QStyle.PM_SliderSpaceAvailable, style_slider, self) x_loc = QStyle.sliderPositionFromValue( self.minimum(), self.maximum(), super(Slider, self).value(), available) buttons = Qt.MouseButtons(self._mid_button) new_pos = QPointF() new_pos.setX(x_loc) mouse_event = QMouseEvent(event.type(), new_pos, self._mid_button, buttons, event.modifiers()) self._start_drag_pos = new_pos self._real_start_drag_pos = event.pos() super(Slider, self).mousePressEvent(mouse_event) self._delta_value = self.value() - self._prev_value self.setValue(self._prev_value) else: super(Slider, self).mousePressEvent(event)
def populateScene(self): self.scene = QGraphicsScene() image = QImage(":/qt4logo.png") # Populate scene xx = 0 nitems = 0 for i in range(-11000, 11000, 110): xx += 1 yy = 0 for j in range(-7000, 7000, 70): yy += 1 x = (i + 11000) / 22000.0 y = (j + 7000) / 14000.0 color = QColor( image.pixel(int(image.width() * x), int(image.height() * y))) item = Chip(color, xx, yy) item.setPos(QPointF(i, j)) self.scene.addItem(item) nitems += 1
def writeData(self, data): max_size = len(data) resolution = 4 if not self.m_buffer: for i in range(XYSeriesIODevice.sampleCount): self.m_buffer.append(QPointF(i, 0)) start = 0 available_samples = int(max_size) // resolution if available_samples < XYSeriesIODevice.sampleCount: start = XYSeriesIODevice.sampleCount - available_samples for s in range(0, start): self.m_buffer[s].setY(self.m_buffer[s + available_samples].y()) pos = 0 for s in range(start, XYSeriesIODevice.sampleCount): y = (1.0 * (data[pos] - 128)) / 128.0 self.m_buffer[s].setY(y) pos += resolution self.m_series.replace(self.m_buffer) return (XYSeriesIODevice.sampleCount - start) * resolution
def position(self, new_position): if type(new_position) in [list, tuple]: self.setPos(QPointF(new_position[0], new_position[1])) elif type(new_position) in [QPoint, QPointF]: self.setPos(new_position)
def line_to(path, cmd, data): target = QPointF(*data) if cmd.islower(): current_pos = path.currentPosition() target += current_pos path.lineTo(target)
def drawMagnifier(self): # First, calculate the magnifier position due to the mouse position watchAreaWidth = 16 watchAreaHeight = 16 watchAreaPixmap = QPixmap() cursor_pos = self.mousePoint watchArea = QRect( QPoint(cursor_pos.x() - watchAreaWidth / 2, cursor_pos.y() - watchAreaHeight / 2), QPoint(cursor_pos.x() + watchAreaWidth / 2, cursor_pos.y() + watchAreaHeight / 2)) if watchArea.left() < 0: watchArea.moveLeft(0) watchArea.moveRight(watchAreaWidth) if self.mousePoint.x() + watchAreaWidth / 2 >= self.screenPixel.width( ): watchArea.moveRight(self.screenPixel.width() - 1) watchArea.moveLeft(watchArea.right() - watchAreaWidth) if self.mousePoint.y() - watchAreaHeight / 2 < 0: watchArea.moveTop(0) watchArea.moveBottom(watchAreaHeight) if self.mousePoint.y( ) + watchAreaHeight / 2 >= self.screenPixel.height(): watchArea.moveBottom(self.screenPixel.height() - 1) watchArea.moveTop(watchArea.bottom() - watchAreaHeight) # tricks to solve the hidpi impact on QCursor.pos() watchArea.setTopLeft( QPoint(watchArea.topLeft().x() * self.scale, watchArea.topLeft().y() * self.scale)) watchArea.setBottomRight( QPoint(watchArea.bottomRight().x() * self.scale, watchArea.bottomRight().y() * self.scale)) watchAreaPixmap = self.screenPixel.copy(watchArea) # second, calculate the magnifier area magnifierAreaWidth = watchAreaWidth * 10 magnifierAreaHeight = watchAreaHeight * 10 fontAreaHeight = 40 cursorSize = 24 magnifierArea = QRectF( QPoint(QCursor.pos().x() + cursorSize, QCursor.pos().y() + cursorSize), QPoint(QCursor.pos().x() + cursorSize + magnifierAreaWidth, QCursor.pos().y() + cursorSize + magnifierAreaHeight)) if magnifierArea.right() >= self.screenPixel.width(): magnifierArea.moveLeft(QCursor.pos().x() - magnifierAreaWidth - cursorSize / 2) if magnifierArea.bottom() + fontAreaHeight >= self.screenPixel.height( ): magnifierArea.moveTop(QCursor.pos().y() - magnifierAreaHeight - cursorSize / 2 - fontAreaHeight) # third, draw the watch area to magnifier area watchAreaScaled = watchAreaPixmap.scaled( QSize(magnifierAreaWidth * self.scale, magnifierAreaHeight * self.scale)) magnifierPixmap = self.graphicsScene.addPixmap(watchAreaScaled) magnifierPixmap.setOffset(magnifierArea.topLeft()) # then draw lines and text self.graphicsScene.addRect(QRectF(magnifierArea), QPen(QColor(255, 255, 255), 2)) self.graphicsScene.addLine( QLineF(QPointF(magnifierArea.center().x(), magnifierArea.top()), QPointF(magnifierArea.center().x(), magnifierArea.bottom())), QPen(QColor(0, 255, 255), 2)) self.graphicsScene.addLine( QLineF(QPointF(magnifierArea.left(), magnifierArea.center().y()), QPointF(magnifierArea.right(), magnifierArea.center().y())), QPen(QColor(0, 255, 255), 2)) # get the rgb of mouse point pointRgb = QColor(self.screenPixel.toImage().pixel(self.mousePoint)) # draw information self.graphicsScene.addRect( QRectF( magnifierArea.bottomLeft(), magnifierArea.bottomRight() + QPoint(0, fontAreaHeight + 30)), QPen(Qt.black), QBrush(Qt.black)) rgbInfo = self.graphicsScene.addSimpleText( ' Rgb: ({0}, {1}, {2})'.format(pointRgb.red(), pointRgb.green(), pointRgb.blue())) rgbInfo.setPos(magnifierArea.bottomLeft() + QPoint(0, 5)) rgbInfo.setPen(QPen(QColor(255, 255, 255), 2)) rect = self.selectedArea.normalized() sizeInfo = self.graphicsScene.addSimpleText(' Size: {0} x {1}'.format( rect.width() * self.scale, rect.height() * self.scale)) sizeInfo.setPos(magnifierArea.bottomLeft() + QPoint(0, 15) + QPoint(0, fontAreaHeight / 2)) sizeInfo.setPen(QPen(QColor(255, 255, 255), 2))
def redraw(self): self.graphicsScene.clear() # draw screenshot self.graphicsScene.addPixmap(self.screenPixel) # prepare for drawing selected area rect = QRectF(self.selectedArea) rect = rect.normalized() topLeftPoint = rect.topLeft() topRightPoint = rect.topRight() bottomLeftPoint = rect.bottomLeft() bottomRightPoint = rect.bottomRight() topMiddlePoint = (topLeftPoint + topRightPoint) / 2 leftMiddlePoint = (topLeftPoint + bottomLeftPoint) / 2 bottomMiddlePoint = (bottomLeftPoint + bottomRightPoint) / 2 rightMiddlePoint = (topRightPoint + bottomRightPoint) / 2 # draw the picture mask mask = QColor(0, 0, 0, 155) if self.selectedArea == QRect(): self.graphicsScene.addRect(0, 0, self.screenPixel.width(), self.screenPixel.height(), QPen(Qt.NoPen), mask) else: self.graphicsScene.addRect(0, 0, self.screenPixel.width(), topRightPoint.y(), QPen(Qt.NoPen), mask) self.graphicsScene.addRect(0, topLeftPoint.y(), topLeftPoint.x(), rect.height(), QPen(Qt.NoPen), mask) self.graphicsScene.addRect( topRightPoint.x(), topRightPoint.y(), self.screenPixel.width() - topRightPoint.x(), rect.height(), QPen(Qt.NoPen), mask) self.graphicsScene.addRect( 0, bottomLeftPoint.y(), self.screenPixel.width(), self.screenPixel.height() - bottomLeftPoint.y(), QPen(Qt.NoPen), mask) # draw the toolBar if self.action != ACTION_SELECT: spacing = 5 # show the toolbar first, then move it to the correct position # because the width of it may be wrong if this is the first time it shows self.tooBar.show() dest = QPointF(rect.bottomRight() - QPointF(self.tooBar.width(), 0) - QPointF(spacing, -spacing)) if dest.x() < spacing: dest.setX(spacing) pen_set_bar_height = self.penSetBar.height( ) if self.penSetBar is not None else 0 if dest.y() + self.tooBar.height( ) + pen_set_bar_height >= self.height(): if rect.top() - self.tooBar.height( ) - pen_set_bar_height < spacing: dest.setY(rect.top() + spacing) else: dest.setY(rect.top() - self.tooBar.height() - pen_set_bar_height - spacing) self.tooBar.move(self.mapToGlobal(dest.toPoint())) if self.penSetBar is not None: self.penSetBar.show() _pen_point = QPoint(dest.toPoint() + QPoint(0, self.tooBar.height() + spacing)) self.penSetBar.move(self.mapToGlobal(_pen_point)) if self.action == ACTION_TEXT: self.penSetBar.showFontWidget() else: self.penSetBar.showPenWidget() else: self.tooBar.hide() if self.penSetBar is not None: self.penSetBar.hide() # draw the list for step in self.drawListResult: self.drawOneStep(step) if self.drawListProcess is not None: self.drawOneStep(self.drawListProcess) if self.action != ACTION_TEXT: self.drawListProcess = None # if self.selectedArea != QRect(): # self.itemsToRemove = [] # # draw the selected rectangle # pen = QPen(QColor(0, 255, 255), 2) # self.itemsToRemove.append(self.graphicsScene.addRect(rect, pen)) # # draw the drag point # radius = QPoint(3, 3) # brush = QBrush(QColor(0, 255, 255)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(topLeftPoint - radius, topLeftPoint + radius), pen, brush)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(topMiddlePoint - radius, topMiddlePoint + radius), pen, brush)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(topRightPoint - radius, topRightPoint + radius), pen, brush)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(leftMiddlePoint - radius, leftMiddlePoint + radius), pen, brush)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(rightMiddlePoint - radius, rightMiddlePoint + radius), pen, brush)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(bottomLeftPoint - radius, bottomLeftPoint + radius), pen, brush)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(bottomMiddlePoint - radius, bottomMiddlePoint + radius), pen, brush)) # self.itemsToRemove.append( # self.graphicsScene.addEllipse(QRectF(bottomRightPoint - radius, bottomRightPoint + radius), pen, brush)) # draw the textedit if self.textPosition is not None: textSpacing = 50 position = QPoint() if self.textPosition.x() + self.textInput.width( ) >= self.screenPixel.width(): position.setX(self.textPosition.x() - self.textInput.width()) else: position.setX(self.textPosition.x()) if self.textRect is not None: if self.textPosition.y() + self.textInput.height( ) + self.textRect.height() >= self.screenPixel.height(): position.setY(self.textPosition.y() - self.textInput.height() - self.textRect.height()) else: position.setY(self.textPosition.y() + self.textRect.height()) else: if self.textPosition.y() + self.textInput.height( ) >= self.screenPixel.height(): position.setY(self.textPosition.y() - self.textInput.height()) else: position.setY(self.textPosition.y()) self.textInput.move(self.mapToGlobal(position)) self.textInput.show() # self.textInput.getFocus() # draw the magnifier if self.action == ACTION_SELECT: self.drawMagnifier() if self.mousePressed: self.drawSizeInfo() if self.action == ACTION_MOVE_SELECTED: self.drawSizeInfo()
def drawOneStep(self, step): """ :type step: tuple """ if step[0] == ACTION_RECT: self.graphicsScene.addRect( QRectF(QPointF(step[1], step[2]), QPointF(step[3], step[4])), step[5]) elif step[0] == ACTION_ELLIPSE: self.graphicsScene.addEllipse( QRectF(QPointF(step[1], step[2]), QPointF(step[3], step[4])), step[5]) elif step[0] == ACTION_ARROW: arrow = QPolygonF() linex = float(step[1] - step[3]) liney = float(step[2] - step[4]) line = sqrt(pow(linex, 2) + pow(liney, 2)) # in case to divided by 0 if line == 0: return sinAngel = liney / line cosAngel = linex / line # sideLength is the length of bottom side of the body of an arrow # arrowSize is the size of the head of an arrow, left and right # sides' size is arrowSize, and the bottom side's size is arrowSize / 2 sideLength = step[5].width() arrowSize = 8 bottomSize = arrowSize / 2 tmpPoint = QPointF(step[3] + arrowSize * sideLength * cosAngel, step[4] + arrowSize * sideLength * sinAngel) point1 = QPointF(step[1] + sideLength * sinAngel, step[2] - sideLength * cosAngel) point2 = QPointF(step[1] - sideLength * sinAngel, step[2] + sideLength * cosAngel) point3 = QPointF(tmpPoint.x() - sideLength * sinAngel, tmpPoint.y() + sideLength * cosAngel) point4 = QPointF(tmpPoint.x() - bottomSize * sideLength * sinAngel, tmpPoint.y() + bottomSize * sideLength * cosAngel) point5 = QPointF(step[3], step[4]) point6 = QPointF(tmpPoint.x() + bottomSize * sideLength * sinAngel, tmpPoint.y() - bottomSize * sideLength * cosAngel) point7 = QPointF(tmpPoint.x() + sideLength * sinAngel, tmpPoint.y() - sideLength * cosAngel) arrow.append(point1) arrow.append(point2) arrow.append(point3) arrow.append(point4) arrow.append(point5) arrow.append(point6) arrow.append(point7) arrow.append(point1) self.graphicsScene.addPolygon(arrow, step[5], step[6]) elif step[0] == ACTION_LINE: self.graphicsScene.addLine( QLineF(QPointF(step[1], step[2]), QPointF(step[3], step[4])), step[5]) elif step[0] == ACTION_FREEPEN: self.graphicsScene.addPath(step[1], step[2]) elif step[0] == ACTION_TEXT: textAdd = self.graphicsScene.addSimpleText(step[1], step[2]) textAdd.setPos(step[3]) textAdd.setBrush(QBrush(step[4])) self.textRect = textAdd.boundingRect()