Ejemplo n.º 1
0
    def paintEvent(self, event):
        """
        Handles the LEDs redraw process

        :param event:
        """
        super().paintEvent(event)

        top_color = self.config.get('colors', 'led_top_row')
        bottom_color = self.config.get('colors', 'led_bottom_row')

        # LEDs
        painter = QPainter(self)
        pen = QPen()
        pen.setWidth(10)
        pinColor = ["black", "red", "grey", "yellow"]

        led_dico = self.digirule.get_led_positions_dic()
        for led in led_dico:
            if led_dico[led] == "pin0Led" or led_dico[led] == "pin1Led":
                # pin Leds can be of 4 different colors
                pen.setColor(QColor(pinColor[self.led_states[led_dico[led]]]))
            elif self.led_states[led_dico[led]]:  # LED active color
                pen.setColor(
                    QColor(top_color if "top" in
                           led_dico[led] else bottom_color))
            else:  # LED inactive color
                pen.setColor(QColor("black"))
            painter.setPen(pen)
            painter.drawPoint(QPoint(led[0], led[1]))
Ejemplo n.º 2
0
    def redraw(self):
        """
        Re-draws the buttons. May be called as initialization method too.
        """
        # Pixmap that contains the painter and the DR
        canvas = QPixmap("assets/" + self.digirule.get_img_name())
        self.setPixmap(canvas)
        painter = QPainter(self.pixmap(
        ))  # Create a painter in which buttons and LEDs are drawn

        translate_matrix = QMatrix()
        offset_scale = self.digirule.get_scale_offset()
        translate_matrix.scale(offset_scale[0], offset_scale[1])
        painter.setMatrix(translate_matrix)

        # Drawing
        pen = QPen()
        pen.setWidth(self.digirule.get_buttons_width())
        pen.setColor(QColor(0, 0, 0, 0))  # Buttons color
        painter.setPen(pen)

        # Buttons
        for btn in self.digirule.get_buttons_positions_dic():
            painter.drawPoint(QPoint(btn[0], btn[1]))

        pen.setWidth(2)
        painter.setPen(pen)

        for btn in self.digirule.get_special_buttons_rects_dic():
            # Draw rectangle given the top-left and bottom-right corners coordinates
            painter.drawRect(self._build_rect(btn))
Ejemplo n.º 3
0
    def paintEvent(self, event):
        """Event"""
        rec = event.rect()
        painter = QPainter()
        painter.begin(self)
        if not self.start_points:
            painter.fillRect(rec, QColor(0, 0, 0, 100))
            self.update_start_points(rec)
        # make mypy happy
        assert isinstance(self.start_points, list)

        if not self.last_point:
            pt = random.choice(self.start_points)
        else:
            rp = random.choice(self.start_points)
            pt = QPoint(
                (self.last_point.x() + rp.x()) / 2,
                (self.last_point.y() + rp.y()) / 2,
            )

        self.last_point = pt
        painter.setPen(QPen(self.color, 0.8))
        painter.drawPoint(pt)
        painter.end()
        # start next update
        self.update()
Ejemplo n.º 4
0
 def draw_mask_point(self, point, pen_size: int = None):
     if pen_size is None:
         pen_size = self.tools.get_size()
     painter = QPainter(self.image_label.pixmap())
     painter.setPen(
         QPen(self.tools.mask_color, pen_size, Qt.SolidLine, Qt.SquareCap,
              Qt.RoundJoin))
     painter.drawPoint(point)
Ejemplo n.º 5
0
 def paint(self,painter:QPainter,view:QPaintDevice):
     painter.begin(view)
     self.setTool(painter)
     x=linearTrans(self.x,self.width,view.width())
     y=linearTrans(self.y,self.height,view.height())
     painter.drawPoint(x,y)
     print("%s:(%d,%d)"%(self.type,x,y))
     painter.end()
     pass
Ejemplo n.º 6
0
    def assert_equal(self):
        __tracebackhide__ = True
        self.end()
        self.different_pixels = 0
        actual_image: QImage = self.actual.device().toImage()
        expected_image: QImage = self.expected.device().toImage()
        diff_pixmap = QPixmap(actual_image.width(), actual_image.height())
        diff = QPainter(diff_pixmap)
        try:
            white = QColor('white')
            diff.fillRect(0, 0, actual_image.width(), actual_image.height(),
                          white)
            for x in range(actual_image.width()):
                for y in range(actual_image.height()):
                    actual_colour = actual_image.pixelColor(x, y)
                    expected_colour = expected_image.pixelColor(x, y)
                    diff.setPen(
                        self.diff_colour(actual_colour, expected_colour, x, y))
                    diff.drawPoint(x, y)
        finally:
            diff.end()
        diff_image: QImage = diff.device().toImage()

        display_diff(actual_image, diff_image, expected_image,
                     self.different_pixels)

        if self.different_pixels == 0:
            return
        actual_image.save(str(self.work_dir / (self.name + '_actual.png')))
        expected_image.save(str(self.work_dir / (self.name + '_expected.png')))
        diff_path = self.work_dir / (self.name + '_diff.png')
        is_saved = diff_image.save(str(diff_path))
        diff_width = self.diff_max_x - self.diff_min_x + 1
        diff_height = self.diff_max_y - self.diff_min_y + 1
        diff_section = QImage(diff_width, diff_height, QImage.Format_RGB32)
        diff_section_painter = QPainter(diff_section)
        try:
            diff_section_painter.drawPixmap(0, 0, diff_width, diff_height,
                                            QPixmap.fromImage(diff_image),
                                            self.diff_min_x, self.diff_min_y,
                                            diff_width, diff_height)
        finally:
            diff_section_painter.end()
        # To see an image dumped in the Travis CI log, copy the text from the
        # log, and paste it in test_pixmap_differ.test_decode_image.
        print(f'Encoded image of differing section '
              f'({self.diff_min_x}, {self.diff_min_y}) - '
              f'({self.diff_max_x}, {self.diff_max_y}):')
        print(encode_image(diff_section))
        message = f'Found {self.different_pixels} different pixels, '
        message += f'see' if is_saved else 'could not write'
        message += f' {diff_path.relative_to(Path(__file__).parent.parent)}.'
        assert self.different_pixels == 0, message
Ejemplo n.º 7
0
    def setup(self):
        if not self.is_set:
            _edge = max([PartyConst.WIDTH, PartyConst.HEIGHT])
            self._stars = np.random.randint(low=0,
                                            high=_edge,
                                            size=((_edge // 250)**2, 2))
            self._pen_link = QPen(QColor('#351c75'), 2, Qt.SolidLine)
            self._lines = []
            min_dist = 100
            for _star in self._stars:
                for _sub_star in self._stars:
                    if 0 < np.linalg.norm(_star - _sub_star) < min_dist:
                        self._lines.append((_star, _sub_star))

            _edge = max([PartyConst.WIDTH, PartyConst.HEIGHT])

            _center = QPoint(self._galaxy.width() // 2,
                             self._galaxy.height() // 2)
            _gradient = QRadialGradient(_center, _edge // 2)
            _gradient.setColorAt(1, QColor('#20124d'))
            _gradient.setColorAt(0, QColor('#351c75'))

            painter = QPainter(self._galaxy)
            painter.fillRect(0, 0, _edge, _edge, _gradient)

            painter.setPen(self._pen_link)
            for _xy1, _xy2 in self._lines:
                _xy1, _xy2 = QPoint(*_xy1), QPoint(*_xy2)
                painter.drawLine(_xy1, _xy2)

            _star_pens = [
                QPen(QColor('#ffffff'), _size, Qt.SolidLine)
                for _size in [1, 2, 3, 4]
            ]
            for _i, (_x, _y) in enumerate(self._stars):
                _xy = QPoint(_x, _y)
                painter.setPen(_star_pens[_i % len(_star_pens)])
                painter.drawPoint(_xy)
            painter.end()
            self._galaxy.save(IMAGE_GALAXY_PATH)
            self.is_set = True
Ejemplo n.º 8
0
    def paint(self, painter: QPainter, model: ShipModel = None):
        assert self.is_set, 'Painter is not set'

        # Draw ship
        if model.is_alive:
            _ship = self._ship_alive
        else:
            _ship = self._ship_dead

        _pixmap = _ship.transformed(model.transform,
                                    mode=Qt.SmoothTransformation)
        _center_ship = self.transform(model.x - _pixmap.width() / 2,
                                      model.y + _pixmap.height() / 2,
                                      is_point=True)

        if 0 <= _center_ship.x() <= self.parent.width(
        ) and 0 <= _center_ship.y() <= self.parent.height():
            painter.drawPixmap(_center_ship, _pixmap)

            # Draw life bar
            _center_bar = self.transform(model.x - self._life_bar_xy[0],
                                         model.y + self._life_bar_xy[1],
                                         is_point=True)
            painter.setPen(QPen(QColor(255, 0, 0), 0, Qt.NoPen))
            painter.setBrush(QBrush(QColor(255, 0, 0)))
            painter.drawRect(_center_bar.x(), _center_bar.y(),
                             self._life_bar_width, 5)
            painter.setBrush(QBrush(QColor(0, 255, 0)))
            painter.drawRect(_center_bar.x(), _center_bar.y(),
                             int(self._life_bar_width * model.life), 5)
            painter.setPen(QPen(QColor(*model.color), 5, Qt.SolidLine))
            _center_title = self.transform(model.x - 100,
                                           model.y + 70,
                                           is_point=True)
            painter.setFont(
                QFont('Open Sans', weight=QFont.Normal, pointSize=8))
            painter.drawText(
                QRect(_center_title.x(), _center_title.y(), 200, 25),
                Qt.AlignHCenter | Qt.AlignTop, '<{}>'.format(model.name))
            painter.setBrush(QBrush(QColor(*model.color)))
            _center_point = self.transform(model.x, model.y, is_point=True)
            painter.drawPoint(_center_point)
        else:
            _xy = QPoint(_center_ship)
            if _center_ship.x() < 0:
                _xy.setX(0)
            if self.parent.width() < _center_ship.x():
                _xy.setX(self.parent.width())

            if _center_ship.y() < 0:
                _xy.setY(0)
            if self.parent.height() < _center_ship.y():
                _xy.setY(self.parent.height())

            painter.setPen(QPen(QColor(0, 0, 0), 30, Qt.SolidLine,
                                Qt.RoundCap))
            painter.drawPoint(_xy)
            painter.setPen(
                QPen(QColor(*model.color), 25, Qt.SolidLine, Qt.RoundCap))
            painter.drawPoint(_xy)
Ejemplo n.º 9
0
    def paintEvent(self, QPaintEvent):
        painter = QPainter()
        painter.begin(self)
        painter.setPen(Qt.NoPen)
        painter.fillRect(self.rect(), QColor(190, 190, 190, 255))

        if self.label_img:
            if self.mouse_press_flag and self.mouse_pos:
                pp = QPainter(self.mask_img)
                if self.eraser_painting_model:
                    pp.setPen(
                        QPen(self.eraser_color, self.eraser_pixle_size,
                             Qt.SolidLine, Qt.RoundCap, Qt.BevelJoin))
                else:
                    pp.setPen(
                        QPen(self.brush_color, self.brush_pixle_size,
                             Qt.SolidLine, Qt.RoundCap, Qt.BevelJoin))

                pp.drawPoint(self.mouse_pos - self.img_rect.topLeft())

            result_pixmap = self.join_pixmap(self.label_img, self.mask_img)
            painter.drawPixmap(self.img_rect, result_pixmap)

        painter.end()
Ejemplo n.º 10
0
    def paintEvent(self, paintEvent: QPaintEvent):
        pen = QPen()
        pen.setJoinStyle(Qt.RoundJoin)
        pen.setCapStyle(Qt.RoundCap)
        painter = QPainter(self)
        painter.translate(self.paintOffset)
        painter.setBackgroundMode(Qt.TransparentMode)
        painter.setRenderHint(QPainter.Antialiasing)

        if self.nodes is not None:
            painted = set()

            def paintNode(node):
                nonlocal painter, painted
                if node in painted:
                    return
                painted.add(node)
                for link in node.links:
                    if link not in painted:
                        painter.drawLine(node.point, link.point)
                        paintNode(link)

            color = self.palette().color(QPalette.Dark)
            pen.setColor(color)
            pen.setWidth(0.50 * self.paintStep)
            painter.setPen(pen)
            for node in self.nodes.values():
                if paintEvent.region().contains(node.point):
                    paintNode(node)

        if self.startNode is not None:
            color = self.palette().color(QPalette.Dark)
            pen.setColor(color)
            pen.setWidth(0.75 * self.paintStep)
            painter.setPen(pen)
            if paintEvent.region().contains(self.startNode.point):
                painter.drawPoint(self.startNode.point)

        if self.finishNode is not None and paintEvent.region().contains(self.finishNode.point):
            color = self.palette().color(QPalette.Dark).darker(120)
            pen.setColor(color)
            pen.setWidth(0.75 * self.paintStep)
            painter.setPen(pen)
            painter.drawPoint(self.finishNode.point)

        if self.player is not None:
            color = self.palette().color(QPalette.Highlight)
            color.setAlpha(196)
            pen.setColor(color)
            pen.setWidth(0.90 * self.paintStep)
            painter.setPen(pen)
            painter.drawPoint(self.player)

        del painter, pen
Ejemplo n.º 11
0
class ImageSegmenterView(QGraphicsView):
    photoClicked = Signal(QPoint)

    def __init__(self, parent):
        super(ImageSegmenterView, self).__init__(parent)
        self._zoom = 0
        self.empty = True
        self._scene = QGraphicsScene(self)
        self._photo = QGraphicsPixmapItem()
        self.image_hidden = False
        self._seglayer = QGraphicsPixmapItem()
        self._seglayer.setOpacity(0.5)
        self._scene.addItem(self._photo)
        self._scene.addItem(self._seglayer)
        self.setScene(self._scene)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
        # self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        # self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setBackgroundBrush(QBrush(QtCore.Qt.darkGray))
        self.setFrameShape(QFrame.NoFrame)

        self.seg_image = None
        self.start = False
        self.prev_point = None
        self.painter = None
        self.segmenter_pen = QPen(QtCore.Qt.green, 30, QtCore.Qt.SolidLine)
        self.segmenter_pen.setCapStyle(QtCore.Qt.RoundCap)
        self.segmenter_pen.setJoinStyle(QtCore.Qt.RoundJoin)
        self.erase = False
        self.changed = False

        self.history = collections.deque(maxlen=10)
        self.future = collections.deque(maxlen=10)

    def hasPhoto(self):
        return not self.empty

    def fitInView(self, scale=True):
        rect = QtCore.QRectF(self._photo.pixmap().rect())
        if not rect.isNull():
            self.setSceneRect(rect)
            if self.hasPhoto():
                unity = self.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))
                self.scale(1 / unity.width(), 1 / unity.height())
                viewrect = self.viewport().rect()
                scenerect = self.transform().mapRect(rect)
                factor = min(viewrect.width() / scenerect.width(),
                             viewrect.height() / scenerect.height())
                self.scale(factor, factor)
            self._zoom = 0

    def setPhoto(self, pixmap=None):
        self._zoom = 0
        if pixmap and not pixmap.isNull():
            self.empty = False
            self.changed = False
            self._photo.setPixmap(pixmap)
            self.seg_image = QImage(pixmap.width(), pixmap.height(),
                                    QImage.Format_ARGB32_Premultiplied)
            self.seg_image.fill(QtCore.Qt.transparent)
            self._seglayer.setPixmap(QPixmap.fromImage(self.seg_image))
        else:
            self._empty = True
            self._photo.setPixmap(QPixmap())
        self.fitInView()

    def save_state(self):
        if self.future is not None:
            while len(self.future) > 0:
                present = self.future.pop()
                del present
        if self.seg_image is not None:
            self.history.append(self.seg_image.copy())

    def clear_history(self):
        while len(self.history) > 0:
            present = self.history.pop()
            del present

    def undo(self):
        if len(self.history) > 0:
            self.future.append(self.seg_image)
            present = self.history.pop()
            self.seg_image = present
            self._seglayer.setPixmap(QPixmap.fromImage(self.seg_image))

    def redo(self):
        if len(self.future) > 0:
            self.history.append(self.seg_image)
            present = self.future.pop()
            self.seg_image = present
            self._seglayer.setPixmap(QPixmap.fromImage(self.seg_image))

    def setSegLayer(self, pixmap=None):
        if not self._photo.pixmap().isNull():
            self.save_state()
            self.seg_image = QImage(pixmap.toImage())
            self._seglayer.setPixmap(QPixmap.fromImage(self.seg_image))

    def resetSegLayer(self):
        if not self._photo.pixmap().isNull():
            self.changed = True
            self.save_state()
            del self.seg_image
            self.seg_image = QImage(self._photo.pixmap().width(),
                                    self._photo.pixmap().height(),
                                    QImage.Format_ARGB32_Premultiplied)
            self.seg_image.fill(QtCore.Qt.transparent)
            self._seglayer.setPixmap(QPixmap.fromImage(self.seg_image))

    def wheelEvent(self, event):
        if self.hasPhoto() and not self.start:
            if event.angleDelta().y() > 0:
                factor = 1.25
                self._zoom += 1
            else:
                factor = 0.8
                self._zoom -= 1
            if self._zoom > 0:
                self.scale(factor, factor)
            elif self._zoom == 0:
                self.fitInView()
            else:
                self._zoom = 0

    def mousePressEvent(self, event):
        if not self._photo.pixmap().isNull():
            if event.button() == QtCore.Qt.LeftButton:
                self.save_state()
                self.start = True
                self.painter = QPainter(self.seg_image)
                if self.erase:
                    self.painter.setCompositionMode(
                        QPainter.CompositionMode_Clear)
                self.painter.setPen(self.segmenter_pen)
                self.paint_point(event.pos())
            elif event.button() == QtCore.Qt.RightButton:
                if not self._photo.pixmap().isNull():
                    self.setDragMode(QGraphicsView.ScrollHandDrag)
                    self.scroll_origin = self.mapToScene(event.pos())
                # if self._photo.isUnderMouse():
                #     self.photoClicked.emit(self.mapToScene(event.pos()).toPoint())
        super(ImageSegmenterView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if not self._photo.pixmap().isNull():
            if self.start:
                self.paint_point(event.pos())
            if event.buttons() & QtCore.Qt.RightButton:
                newpoint = self.mapToScene(event.pos())
                translation = newpoint - self.scroll_origin
                self.translate(translation.x(), translation.y())
                self.scroll_origin = self.mapToScene(event.pos())
        super(ImageSegmenterView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if not self._photo.pixmap().isNull():
            if self.start:
                self.start = False
                self.prev_point = None
                self.painter.end()
            if self.dragMode() == QGraphicsView.ScrollHandDrag:
                self.setDragMode(QGraphicsView.NoDrag)

    def paint_point(self, pos):
        self.changed = True
        pos = self.mapToScene(pos).toPoint()
        if self.prev_point is not None:
            self.painter.drawLine(self.prev_point, pos)
        else:
            self.painter.drawPoint(pos)
        self.prev_point = pos
        self._seglayer.setPixmap(QPixmap.fromImage(self.seg_image))

    def set_foreground(self):
        self.erase = False
        self.segmenter_pen.setColor(QtCore.Qt.green)

    def set_possible_foreground(self):
        self.erase = False
        self.segmenter_pen.setColor(QtCore.Qt.blue)

    def set_possible_background(self):
        self.erase = True
        self.segmenter_pen.setColor(QtCore.Qt.transparent)

    def set_background(self):
        self.erase = False
        self.segmenter_pen.setColor(QtCore.Qt.red)

    def set_pen_size(self, size):
        self.segmenter_pen.setWidth(size)

    def set_opacity(self, value):
        self._seglayer.setOpacity(value / 100)

    def hide_image(self):
        if self.image_hidden:
            self._photo.setOpacity(1)
            self.image_hidden = False
        else:
            self._photo.setOpacity(0)
            self.image_hidden = True
Ejemplo n.º 12
0
    def draw_mini_map(self, painter, is_full=False):
        _pixmap_minimap = QPixmap(
            QSize(min([self.width(), self.height()]),
                  min([self.width(), self.height()]))) if is_full else QPixmap(
                      QSize(350, 350))
        if is_full:
            _p_origin = QPoint((self.width() - _pixmap_minimap.width()) // 2,
                               (self.height() - _pixmap_minimap.height()) // 2)
        else:
            _p_origin = QPoint(self.width() - _pixmap_minimap.width(),
                               self.height() - _pixmap_minimap.height())
        _pixmap_minimap.fill(QColor('#00284d'))

        # DRAW DEAD ZONE
        _dz_radius = self.controller.get_dead_zone_radius()
        _xy = QPoint(*self.controller.get_dead_zone_center().tolist())

        # GET MOBILE OBJECTS
        _model_ships = self.controller.get_data_from_players(enemy_only=False)
        _model_bolts = self.controller.get_data_from_bolts()
        _model_asteroids = self.controller.get_data_from_asteroids()

        # SET MINI MAP
        _w_ratio = _pixmap_minimap.width() / (PartyConst.WIDTH * 1.25)
        _h_ratio = _pixmap_minimap.height() / (PartyConst.HEIGHT * 1.25)

        _minimap_painter = QPainter(_pixmap_minimap)
        _minimap_painter.setOpacity(1)
        for _ship in _model_ships:
            _w = _ship.radius * _w_ratio
            if _w < 3:
                _w = 3
            _x, _y = int(
                _ship.x * _w_ratio) + _pixmap_minimap.width() // 2, int(
                    _ship.y * _h_ratio) + _pixmap_minimap.height() // 2

            if _ship.is_alive:
                _factor_1 = (time.time() * 2) % 2
                _factor_2 = (time.time() * 2 + .5) % 2

                _minimap_painter.setPen(
                    QPen(QColor('#ffffff'), 1, Qt.SolidLine))
                _minimap_painter.setOpacity(1 - _factor_1)
                _minimap_painter.drawEllipse(QPoint(_x, _y),
                                             int(20 * _factor_1),
                                             int(20 * _factor_1))
                _minimap_painter.setOpacity(1 - _factor_2)
                _minimap_painter.drawEllipse(QPoint(_x, _y),
                                             int(20 * _factor_2),
                                             int(20 * _factor_2))

            _minimap_painter.setPen(
                QPen(QColor(*_ship.color), _w, Qt.SolidLine))
            _minimap_painter.setOpacity(1)
            _minimap_painter.drawPoint(_x, _y)

        for _astroid in _model_asteroids:
            _w = _astroid.radius * _w_ratio
            if _w < 5:
                _w = 5
            _pen = QPen(QColor('#ffb86c'), _w, Qt.SolidLine)
            _pen.setCapStyle(Qt.RoundCap)
            _minimap_painter.setPen(_pen)
            _x, _y = int(
                _astroid.x * _w_ratio) + _pixmap_minimap.width() // 2, int(
                    _astroid.y * _h_ratio) + _pixmap_minimap.height() // 2
            _minimap_painter.drawPoint(_x, _y)
        for _bolt in _model_bolts:
            _w = _bolt.radius * _w_ratio
            if _w < 1:
                _w = 1
            _minimap_painter.setPen(QPen(QColor('#ff5555'), _w, Qt.SolidLine))
            _x, _y = int(
                _bolt.x * _w_ratio) + _pixmap_minimap.width() // 2, int(
                    _bolt.y * _h_ratio) + _pixmap_minimap.height() // 2
            _minimap_painter.drawPoint(_x, _y)

        _xy.setX(_xy.x() * _w_ratio + _pixmap_minimap.width() // 2)
        _xy.setY(_xy.y() * _h_ratio + _pixmap_minimap.height() // 2)

        _minimap_painter.setPen(QPen(QColor('#8be9fd'), 3, Qt.SolidLine))
        _minimap_painter.drawEllipse(_xy, _dz_radius * _w_ratio,
                                     _dz_radius * _h_ratio)

        if not is_full:
            _minimap_painter.setPen(QPen(QColor('#ffffff'), 1, Qt.SolidLine))
            _x = -self.camera_pst.x() * _w_ratio + _pixmap_minimap.width() // 2
            _y = self.camera_pst.y() * _h_ratio + _pixmap_minimap.height() // 2
            _w = self.width() * _w_ratio
            _h = self.height() * _h_ratio
            _minimap_painter.drawRect(_x, _y - _h, _w, _h)
        _minimap_painter.end()

        _pixmap_minimap = _pixmap_minimap.transformed(QTransform().scale(
            1, -1))

        painter.setOpacity(1 if is_full else .75)
        painter.drawPixmap(_p_origin, _pixmap_minimap)
Ejemplo n.º 13
0
class QCanvas(QLabel):
    def __init__(self, parent: QWidget, window: MainWindow):
        super().__init__(parent)
        self.pWindow = window
        self.strokeX = []
        self.strokeY = []
        self.strokeT = []
        self.timing = QTime()
        self.timing.start()
        self.paused = 0
        self.painter = QPainter()
        self.setStyleSheet("background-color: white;")
    
    """ EVENT: MOUSE CLICK/PRESS """
    def mousePressEvent(self, event: QMouseEvent) -> None:
        self.timing.restart()
        self.strokeX.append(list())
        self.strokeY.append(list())
        self.strokeT.append(list())
        self.strokeX[-1].append(event.x())
        self.strokeY[-1].append(event.y())
        self.strokeT[-1].append(self.paused)
        return super().mousePressEvent(event)

    """ EVENT: MOUSE MOVE WHILE PRESSED """
    def mouseMoveEvent(self, event: QMouseEvent) -> None:
        if event.x() > 0 and event.y() > 0 and event.x() <= self.width() and event.y() <= self.height():
            # IF DRAWING IS NOT JUST A MERE POINT...
            if len(self.strokeT[-1]) == 1:
                self.timing.restart()
                self.paused += 1
            self.strokeX[-1].append(event.x())
            self.strokeY[-1].append(event.y())
            self.strokeT[-1].append(self.timing.elapsed() + self.paused)
        else: return
        return super().mouseMoveEvent(event)

    """ EVENT: MOUSE RELEASE """
    def mouseReleaseEvent(self, event: QMouseEvent) -> None:
        # TO ABLE TO RECOGNIZE POINTS AS PART OF THE DRAWING...
        if len(self.strokeT[-1]) == 1:
            self.paused += 1
        # OTHERWISE, CHECKPOINTS THE MILLISECONDS AS FOLLOWS.
        else:
            self.paused += (self.timing.elapsed() + 1)
        return super().mouseReleaseEvent(event)

    """ EVENT: UPDATE PAINT 
        => Beware, every time paintEvent updates removes previous drawings.
        Therefore, store the data of previous drawing to prevent being erased.
    """
    def paintEvent(self, event: QPaintEvent) -> None:
        pen = QPen()
        pen.setWidth(4)
        pen.setColor(Qt.color1)  
        self.painter.begin(self)
        self.painter.setPen(pen)
        if len(self.strokeX) != 0:
            for stroke in range(len(self.strokeX)):
                if len(self.strokeX[stroke]) == 1:
                    self.painter.drawPoint(self.strokeX[stroke][0], self.strokeY[stroke][0])
                else:
                    for index in range(len(self.strokeX[stroke]) - 1):
                        self.painter.drawLine(self.strokeX[stroke][index], self.strokeY[stroke][index], self.strokeX[stroke][index+1], self.strokeY[stroke][index+1])
        self.painter.end()
        self.update()
        return super().paintEvent(event)

    """ EVENT: UPON SHOWN """
    def showEvent(self, event: QShowEvent) -> None:
        self.blankCanvas()
        return super().showEvent(event)

    """ METHOD: CREATE CANVAS """
    def blankCanvas(self) -> None:
        margin = self.parentWidget().layout().margin()
        width = self.topLevelWidget().width()
        height = self.topLevelWidget().height()
        for index in range(self.parentWidget().layout().count()):
            if index != self.parentWidget().layout().indexOf(self): 
                height -= (self.parentWidget().layout().itemAt(index).widget().height() + margin * 2)
        canvas = QBitmap(width - margin * 2, height)
        canvas.clear()
        self.setPixmap(canvas)
        self.update()

    """ METHOD: RESET CANVAS """
    def resetCanvas(self) -> None:
        self.strokeX = []
        self.strokeY = []
        self.strokeT = []
        self.paused = 0
        self.blankCanvas()

    """ METHOD: UNDO CANVAS """
    def undoCanvas(self) -> None:
        try:
            self.paused = self.strokeT[-1][0]
            self.strokeX.pop()
            self.strokeY.pop()
            self.strokeT.pop()
        except IndexError:
            print("The canvas is completely empty!")
        self.blankCanvas()