Example #1
0
    def draw_needle(self, painter):
        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        painter.rotate(self._angle)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)

        painter.setPen(QPen(Qt.NoPen))
        painter.setBrush(self.palette().brush(QPalette.WindowText))

        painter.drawPolygon(
            QPolygon([
                QPoint(-10, 0),
                QPoint(0, -45),
                QPoint(10, 0),
                QPoint(0, 45),
                QPoint(-10, 0)
            ]))

        painter.setBrush(Qt.red)

        painter.drawPolygon(
            QPolygon([
                QPoint(-5, -25),
                QPoint(0, -45),
                QPoint(5, -25),
                QPoint(0, -30),
                QPoint(-5, -25)
            ]))

        painter.restore()
Example #2
0
    def drawNeedle(self, painter):
        """
        Aguja, (fondo y punta)
        """

        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        painter.rotate(self._angle)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)
        painter.setPen(QPen(Qt.NoPen))

        painter.setBrush(self.palette().brush(QPalette.Shadow))
        painter.drawPolygon(
            QPolygon([
                QPoint(-10, 0),
                QPoint(0, -45),
                QPoint(10, 0),
                QPoint(0, 45),
                QPoint(-10, 0)
            ]))

        # painter.setBrush(self.palette().brush(QPalette.Highlight))
        painter.setBrush(self.colorMarcasCompass)
        painter.drawPolygon(
            # QPolygon([QPoint(-5, -25), QPoint(0, -45), QPoint(5, -25),
            #             QPoint(0, -30), QPoint(-5, -25)])
            QPolygon([
                QPoint(-10, 0),
                QPoint(0, -45),
                QPoint(10, 0),
                QPoint(-10, 0)
            ]))
        painter.restore()
Example #3
0
    def selectpoly_copy(self):
        """
        Copy a polygon region from the current image, returning it.

        Create a mask for the selected area, and use it to blank
        out non-selected regions. Then get the bounding rect of the
        selection and crop to produce the smallest possible image.

        :return: QPixmap of the copied region.
        """
        self.timer_cleanup()

        pixmap = self.pixmap().copy()
        bitmap = QBitmap(*CANVAS_DIMENSIONS)
        bitmap.clear()  # Starts with random data visible.

        p = QPainter(bitmap)
        # Construct a mask where the user selected area will be kept,
        # the rest removed from the image is transparent.
        userpoly = QPolygon(self.history_pos + [self.current_pos])
        p.setPen(QPen(Qt.color1))
        p.setBrush(QBrush(Qt.color1))  # Solid color, Qt.color1 == bit on.
        p.drawPolygon(userpoly)
        p.end()

        # Set our created mask on the image.
        pixmap.setMask(bitmap)

        # Calculate the bounding rect and return a copy of that region.
        return pixmap.copy(userpoly.boundingRect())
Example #4
0
    def draw(self, gp):
        gp.setPen(QPen(Qt.black, 1, Qt.SolidLine))
        L = int(self.line.text())
        k = float(self.line1.text())
        N = int(self.line2.text())

        A1 = QPoint(0, 0)
        B1 = QPoint(L, 0)
        C1 = QPoint(L, L)
        D1 = QPoint(0, L)
        # for (i = 0; i < n; i++) {
        #     printf("%f %f\n", x + r * Math.cos(2 * Math.PI * i / n), y + r * Math.sin(2 * Math.PI * i / n));
        # }

        points = QPolygon([A1, B1, C1, D1])
        gp.drawPolygon(points)

        for i in range(N):
            A2 = QPoint(k * A1.x() + (1 - k) * B1.x(),
                        k * A1.y() + (1 - k) * B1.y())
            B2 = QPoint(k * B1.x() + (1 - k) * C1.x(),
                        k * B1.y() + (1 - k) * C1.y())
            C2 = QPoint(k * C1.x() + (1 - k) * D1.x(),
                        k * C1.y() + (1 - k) * D1.y())
            D2 = QPoint(k * D1.x() + (1 - k) * A1.x(),
                        k * D1.y() + (1 - k) * A1.y())

            points = QPolygon([A2, B2, C2, D2])
            gp.drawPolygon(points)
            A1, B1, C1, D1 = A2, B2, C2, D2
 def __init__(self):
     """
     Constructor
     """
     super(SnapshotFreehandGrabber, self).__init__(
         None,
         Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint |
         Qt.FramelessWindowHint | Qt.Tool)
     
     self.__selection = QPolygon()
     self.__mouseDown = False
     self.__newSelection = False
     self.__handleSize = 10
     self.__showHelp = True
     self.__grabbing = False
     self.__dragStartPoint = QPoint()
     self.__selectionBeforeDrag = QPolygon()
     self.__locale = QLocale()
     
     self.__helpTextRect = QRect()
     self.__helpText = self.tr(
         "Select a region using the mouse. To take the snapshot,"
         " press the Enter key or double click. Press Esc to quit.")
     
     self.__pixmap = QPixmap()
     self.__pBefore = QPoint()
     
     self.setMouseTracking(True)
     
     QTimer.singleShot(200, self.__initialize)
Example #6
0
    def _drawIcon(self, color=Qt.black):
        self.setForeground(QBrush(color))

        if self.isRootNode:
            pixmap = QPixmap(20, 20)
            pixmap.fill(Qt.transparent)
            painter = QPainter()
            painter.begin(pixmap)
            pen = QPen(color)
            pen.setWidth(1)
            painter.setPen(pen)
            painter.setBrush(color)
            painter.setRenderHint(QPainter.Antialiasing)
            if not self.isExpanded:
                arrowRightPolygon = [
                    QPoint(6, 6), QPoint(6, 14),
                    QPoint(14, 10)
                ]
                painter.drawPolygon(QPolygon(arrowRightPolygon))
            else:
                arrowDownPolygon = [
                    QPoint(6, 6), QPoint(15, 6),
                    QPoint(10, 14)
                ]
                painter.drawPolygon(QPolygon(arrowDownPolygon))
            painter.end()
            self.setIcon(QIcon(pixmap))
    def drawNeedle(self, painter):
        painter.save()
        painter.translate(self.width() / 2, self.height() / 2)
        painter.rotate(self.angle)
        scale = min((self.width() - self.margins) / 120,
                    (self.height() - self.margins) / 120)
        painter.scale(scale, scale)

        painter.setPen(QPen(Qt.NoPen))
        painter.setBrush(QColor(Qt.black))
        painter.drawPolygon(
            QPolygon([
                QPoint(-10, 0),
                QPoint(0, -45),
                QPoint(10, 0),
                QPoint(0, 45),
                QPoint(-10, 0)
            ]))

        painter.setBrush(QColor(Qt.red))
        painter.drawPolygon(
            QPolygon([
                QPoint(-5, -25),
                QPoint(0, -45),
                QPoint(5, -25),
                QPoint(0, -30),
                QPoint(-5, -25)
            ]))
        painter.restore()
Example #8
0
    def __init__(self, parent=None):

        super(PyAnalogClock, self).__init__(parent)

        self.timeZoneOffset = 0

        timer = QTimer(self)
        timer.timeout.connect(self.update)
        timer.timeout.connect(self.updateTime)
        timer.start(1000)

        self.setWindowTitle("Analog Clock")
        self.resize(200, 200)

        self.hourHand = QPolygon([
            QPoint(7, 8),
            QPoint(-7, 8),
            QPoint(0, -40)
        ])
        self.minuteHand = QPolygon([
            QPoint(7, 8),
            QPoint(-7, 8),
            QPoint(0, -70)
        ])

        self.hourColor = QColor(0, 127, 0)
        self.minuteColor = QColor(0, 127, 127, 191)
    def drawing(self, qp):
        if self.k == 0:
            qp.setBrush(QColor(choice(self.colors)))
            points = QPolygon([QPoint(randint(1, 300), randint(1, 300)),
                               QPoint(randint(1, 300), randint(1, 300)),
                               QPoint(randint(1, 300), randint(1, 300)),
                               QPoint(randint(1, 300), randint(1, 300))])
            qp.drawPolygon(points)
        elif self.x > -1 and self.y > -1 and self.k == 1:
            qp.setBrush(QColor(choice(self.colors)))
            qp.drawRect(self.x, self.y, randint(1, 100), randint(1, 100))
            ex.show()

        elif self.x > -1 and self.y > -1 and self.k == -1:

            qp.setBrush(QColor(choice(self.colors)))
            a = randint(1, 100)
            qp.drawEllipse(self.x, self.y, a, a)

        elif self.x > -1 and self.y > -1 and self.k == 2:
            qp.setBrush(QColor(choice(self.colors)))
            points = QPolygon([QPoint((self.x + self.x // 2) + randint(1, self.x),
                                      (self.y - self.y // 2) + randint(1, self.y)),
                               QPoint(self.x, self.y),
                               QPoint(self.x // 2, self.y * 2)])
            qp.drawPolygon(points)
Example #10
0
def counterClockwise(polygon: []):
    poly = QPolygon()
    for p in polygon:
        poly.append(QPoint(p[0], p[1]))
    rect = poly.boundingRect()
    center = rect.center()

    return polygon
Example #11
0
 def mouseReleaseEvent(self, event):
     if self.buttonpressed == Qt.RightButton:
         pass # appeller le menu
     #self.current.remove(self.current.size()-1)
     self.paths.append((self.current, self.color, self.width))
     self.current = QPolygon()
     self.buttonpressed = -1
     self.update()
    def paintEvent(self, event):
        qp = QtGui.QPainter(self)

        for r in self.rect_list:
            qp.setBrush(QtGui.QBrush(QtGui.QColor(100, 10, 10,
                                                  40)))  # module color
            qp.drawRect(QtCore.QRect(r.rect_begin,
                                     r.rect_end))  # Draw module rectangle
            qp.drawText((r.rect_begin + r.rect_end) / 2,
                        r.center_text)  # Write the name of module rectangle

            in_order = 0
            out_order = 0
            inout_order = 0

            # Draw input ports and their names
            for i in r.in_port_list:
                # Write the port name
                qp.drawText(
                    r.rect_begin + QtCore.QPoint(
                        5, int(r.Tri_In_F / 2 + r.Tri_In_F * in_order)),
                    i.text)
                in_order = in_order + 1

                polygon = QPolygon(i.points)
                qp.setBrush(QtGui.QBrush(QtGui.QColor(
                    0, 0, 255, 127)))  # input port color
                qp.drawPolygon(polygon)

            # Draw output ports and their names
            for i in r.out_port_list:
                # Write the port name
                qp.drawText(
                    r.rect_end + QtCore.QPoint(
                        int(r.Tri_In_H + 5),
                        int(-(r.rect_end.y() - r.rect_begin.y()) +
                            r.Tri_In_F / 2 + r.Tri_In_F * out_order)), i.text)
                out_order = out_order + 1

                polygon = QPolygon(i.points)
                qp.setBrush(QtGui.QBrush(QtGui.QColor(
                    0, 0, 255, 127)))  # output port color
                qp.drawPolygon(polygon)

            # Draw inout ports and their names
            for i in r.inout_port_list:
                # Write the port name
                qp.drawText(
                    QtCore.QPoint(
                        int(r.rect_begin.x() + 5),
                        int(r.rect_end.y() - r.Tri_In_F / 2 -
                            r.Tri_In_F * inout_order)), i.text)
                inout_order = inout_order + 1

                polygon = QPolygon(i.points)
                qp.setBrush(QtGui.QBrush(QtGui.QColor(
                    0, 0, 255, 127)))  # inout port color
                qp.drawPolygon(polygon)
Example #13
0
    def draw(self, image):
        qp = QPainter(image)

        qp.setPen(QPen(self.drawContext.stroke, self.drawContext.width))
        qp.drawPolyline(QPolygon(self.points))

        qp.setPen(QPen(Qt.transparent, 0))
        qp.setBrush(self.drawContext.fill)
        qp.drawPolygon(QPolygon(self.points))
Example #14
0
 def initUI(self):
     self.paths = []
     self.current = QPolygon()
     self.select = QPolygon()
     self.ctrl = False
     self.color = QColor("black")
     self.width = 1
     self.buttonpressed = -1
     self.selected_poly = []
Example #15
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     width, height = self.width(), self.height()
     polygon = QPolygon()
     for i, rate in enumerate(self.loads):
         x = width - i * self.pointDistance
         y = height - rate * height
         if x < self.boxWidth:
             break
         polygon.append(QPoint(x, y))
     painter = QPainter(self)
     pen = QPen()
     pen.setColor(Qt.darkGreen)
     painter.setPen(pen)
     painter.setRenderHint(QPainter.Antialiasing, True)
     #画网格
     painter.setOpacity(0.5)
     gridSize = self.pointDistance * 4
     deltaX = (width - self.boxWidth) % gridSize + self.boxWidth
     deltaY = height % gridSize
     for i in range(int(width / gridSize)):
         x = deltaX + gridSize * i
         painter.drawLine(x, 0, x, height)
     for j in range(int(height / gridSize)):
         y = j * gridSize + deltaY
         painter.drawLine(self.boxWidth, y, width, y)
     #画折线
     pen.setColor(Qt.darkCyan)
     pen.setWidth(2)
     painter.setPen(pen)
     painter.setOpacity(1)
     painter.drawPolyline(polygon)
     #画展示框
     if len(self.loads) > 0:
         rate = self.loads[0]
     else:
         rate = 1.0
     rect1 = QRect(4, height * 0.05, self.boxWidth - 9, height * 0.7)
     rect2 = QRect(4, height * 0.8, self.boxWidth - 9, height * 0.2)
     centerX = int(rect1.width() / 2) + 1
     pen.setWidth(1)
     for i in range(rect1.height()):
         if i % 4 == 0:
             continue
         if (rect1.height() - i) / rect1.height() > rate:
             pen.setColor(Qt.darkGreen)
         else:
             pen.setColor(Qt.green)
         painter.setPen(pen)
         for j in range(rect1.width()):
             if centerX - 1 <= j <= centerX + 1:
                 continue
             painter.drawPoint(rect1.x() + j, rect1.y() + i)
     pen.setColor(Qt.black)
     painter.setPen(pen)
     painter.drawText(rect2, Qt.AlignHCenter | Qt.AlignVCenter, str(int(rate * 100)) + "%")
class AnalogClock(QWidget):
    hourHand = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -40)])

    minuteHand = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -70)])

    hourColor = QColor(127, 0, 127)
    minuteColor = QColor(0, 127, 127, 191)

    def __init__(self, parent=None):
        super(AnalogClock, self).__init__(parent)

        timer = QTimer(self)
        timer.timeout.connect(self.update)
        timer.start(1000)

        self.setWindowTitle("Analog Clock")
        self.resize(200, 200)

    def paintEvent(self, event):
        side = min(self.width(), self.height())
        time = QTime.currentTime()

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogClock.hourColor)

        painter.save()
        painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)))
        painter.drawConvexPolygon(AnalogClock.hourHand)
        painter.restore()

        painter.setPen(AnalogClock.hourColor)

        for i in range(12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogClock.minuteColor)

        painter.save()
        painter.rotate(6.0 * (time.minute() + time.second() / 60.0))
        painter.drawConvexPolygon(AnalogClock.minuteHand)
        painter.restore()

        painter.setPen(AnalogClock.minuteColor)

        for j in range(60):
            if (j % 5) != 0:
                painter.drawLine(92, 0, 96, 0)
            painter.rotate(6.0)
Example #17
0
    def paintEvent(self, QPaintEvent):
        painter = QPainter(self)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(QColor("#FF9966")))
        painter.setRenderHints(QPainter.Antialiasing)  #抗锯齿

        #绘制过程
        polygon = QPolygon()
        polygon.setPoints([10, 0, 10, 40, 40, 20])
        painter.drawPolygon(polygon)
        self.update()
Example #18
0
    def drawNeedle(self, painter):
        painter.save()
        # Set up painter
        painter.translate(self.width() / 2, self.height() / 2)
        scale = min((self.width() - self._margins) / 120.0,
                    (self.height() - self._margins) / 120.0)
        painter.scale(scale, scale)
        painter.setPen(QPen(Qtc.NoPen))

        # Rotate surface for painting
        intAngle = int(round(self._angle))
        painter.rotate(intAngle)

        # Draw the full black needle first if needed
        if self.needleType == NeedleFull:
            needleTailBrush = self.palette().brush(QPalette.Shadow)
            needleTailColor = QColor(self.needleBodyColor)
            needleTailBrush.setColor(needleTailColor)
            painter.setBrush(needleTailBrush)

            painter.drawPolygon(QPolygon([QPoint(-6, 0), QPoint(0, -45), QPoint(6, 0),
                                          QPoint(0, 45), QPoint(-6, 0)]))

        # Now draw the red tip (on top of the black needle)
        needleTipBrush = self.palette().brush(QPalette.Highlight)
        needleTipColor = QColor(self.needleTipColor)
        needleTipBrush.setColor(needleTipColor)
        painter.setBrush(needleTipBrush)

        # First QPoint is the center bottom apex of the needle
        painter.drawPolygon(QPolygon([QPoint(-3, -24), QPoint(0, -45), QPoint(3, -23),
                                      QPoint(0, -30), QPoint(-3, -23)]))

        if self.needleType == NeedleMirrored:
            # Rotate
            # Need to account for the initial rotation to see how much more to rotate it.
            if (intAngle == 90 or intAngle == -90 or intAngle == 270):
                mirrorRotation = 180
            else:
                mirrorRotation = 180 - intAngle - intAngle
            painter.rotate(mirrorRotation)

            # Paint shadowed indicator
            needleTipBrush = self.palette().brush(QPalette.Highlight)
            needleTipColor = Qtc.gray
            needleTipBrush.setColor(needleTipColor)
            painter.setBrush(needleTipBrush)

            painter.drawPolygon(
                QPolygon([QPoint(-3, -25), QPoint(0, -45), QPoint(3, -25),
                          QPoint(0, -30), QPoint(-3, -25)])
            )

        painter.restore()
Example #19
0
    def mousePressEvent(self, event):
        self.select = QPolygon()
        self.selected_poly = []
        self.buttonpressed = event.button()
        if self.buttonpressed == Qt.RightButton:
            self.selected = QPolygon()

            self.select.append(event.pos())
        else:
            self.current = QPolygon()
            self.current.append(event.pos())
        self.update()
Example #20
0
    def __init__(self, parent=None):
        super(MyLabel, self).__init__(parent)
        self.clicked = pyqtSignal()

        self.x0 = self.y0 = self.x1 = self.y1 = 0
        self.flag = False
        self.rect = QRect()
        self.pFlag = False
        self.chosen_points = QPolygon()

        self.path = QPainterPath()
        self.num = 0
Example #21
0
    def paintEvent(self, event):
        painter = QPainter(self)

        # complete graph ratio
        scale, translation = self._get_scale_translation()

        if self.need_draw_grid:
            self.draw_grid(scale, translation)

        painter.drawPixmap(QPoint(), self.pixmap)

        ############ EXTERIOR #################################
        painter.setPen(self.external_contour_pen)
        exterior_coords_on_screen = [
            QPoint(*tuple(p * scale + translation))
            for p in self.current_polygon_exterior
        ]
        painter.drawPolyline(QPolygon(exterior_coords_on_screen))

        ############ INTERIOR #################################
        painter.setPen(self.internal_contour_pen)
        interior_coords_list = []
        for current_polygon_interior in self.current_polygon_interiors:
            interior_coords_on_screen = [
                QPoint(*tuple(p * scale + translation))
                for p in current_polygon_interior
            ]
            painter.drawPolyline(QPolygon(interior_coords_on_screen))
            interior_coords_list.append(interior_coords_on_screen)

        ####################### Points of each point ##########
        # Draw selected Point in different color
        if self.current_selected_tuple is not None and self.current_selected_tuple[
                0] == 'exterior':
            exterior_coords_on_screen = self.draw_exterior_selected_point(
                exterior_coords_on_screen, painter)

        if self.current_selected_tuple is not None and self.current_selected_tuple[
                0] == 'interior':
            interior_coords_list = self.draw_interior_selected_point(
                interior_coords_list, painter)

        painter.setPen(self.external_point_pen)
        painter.drawPoints(QPolygon(exterior_coords_on_screen))

        painter.setPen(self.internal_point_pen)
        for interior_coord in interior_coords_list:
            painter.drawPoints(QPolygon(interior_coord))

        ###################### Each tile in the solution ###############
        if self.current_best_solution is not None:
            self.draw_solution(painter)
Example #22
0
    def paintRadarChart(self,
                        scores,
                        scoresValue,
                        x=255,
                        y=270,
                        r=160,
                        n=6,
                        m=5):
        # (x, y)为中心画雷达图,r为大小,n为边数,m为几等分
        # scoresValue在0到1之间,展示雷达图用
        painter = QPainter(self)
        angle_0 = 0  # 起始位置弧度,向上为0,顺时针为正
        scoresName = ['Ce/s', '3BV/s', 'RTime', 'STNC', 'IOE', 'RQP']

        painter.setPen(self.pen1)
        painter.setFont(QFont('Arial', 16))  # 设置字体和大小

        for j in range(1, m + 1):
            points = []
            for i in range(n):
                angle_s = angle_0 + i * 6.2831853 / n
                angle_t = angle_0 + (i + 1) * 6.2831853 / n
                r0 = j / m * r
                x_s = int(x + r0 * math.cos(angle_s))
                y_s = int(y - r0 * math.sin(angle_s))
                points.append(QtCore.QPoint(x_s, y_s))
            painter.drawPolygon(QPolygon(points))

        points = []
        for i in range(n):
            angle_s = angle_0 + i * 6.2831853 / n
            angle_t = angle_0 + (i + 1) * 6.2831853 / n

            x_s = int(x + r * math.cos(angle_s))
            y_s = int(y - r * math.sin(angle_s))
            painter.setPen(self.pen1)
            painter.drawLine(x, y, x_s, y_s)
            x_s = int(x + r0 * 1.23 * math.cos(angle_s))
            y_s = int(y - r0 * 1.23 * math.sin(angle_s))
            painter.setPen(self.pen3)
            painter.drawText(QtCore.QRectF(x_s - 65, y_s - 30, 120,
                                           60), QtCore.Qt.AlignCenter,
                             scoresName[i] + "\n" + scores[scoresName[i]])
            # painter.drawText(QtCore.QRectF(50,70,100,130), QtCore.Qt.AlignCenter, "abcdefg\nhijklmn")
            x_s = int(x + scoresValue[i] * r * math.cos(angle_s))
            y_s = int(y - scoresValue[i] * r * math.sin(angle_s))
            points.append(QtCore.QPoint(x_s, y_s))
        painter.setPen(self.pen2)

        painter.setBrush(self.brush)
        painter.drawPolygon(QPolygon(points))
Example #23
0
    def toScreenPolygon(self,listVertex):
        listPoints = []
        nPoints = 0
        for i in range(len(listVertex)):
            vertex = listVertex[i]
            vertex = self.toScreenVertex(vertex)
            listPoints.append(vertex.x)
            listPoints.append(vertex.y)
            nPoints+=1

        polygon = QPolygon()
        polygon.setPoints( listPoints)

        return polygon
Example #24
0
    def mouseReleaseEvent(self, event):
        super(GraphicsScene, self).mousePressEvent(event)

        pos = event.scenePos()

        if event.button() == Qt.LeftButton:
            self.draw_switch = False

            if pos.x()>=0 \
            and pos.x()<self.pixmapunderground.width() \
            and pos.y()>=0 \
            and pos.y()<self.pixmapunderground.height():
                label = self.dialog.gettext()  #ask for label

                if label[1] == True and len(label[0]) > 0 and len(
                        self.poly) > 0:  #if user input a label

                    # save the label on backend
                    if len(self.poly) > 1:
                        # point the label on screen
                        poly = QPolygon()
                        for p in self.poly:
                            poly.append(p.toPoint())
                            # print(p)
                        brush = QBrush()
                        labelcolor = QColor(*[
                            c * 255
                            for c in plt.get_cmap('tab10').colors[int(label[0])
                                                                  - 1]
                        ])
                        brush.setColor(labelcolor)
                        brush.setStyle(Qt.SolidPattern)
                        self.addPolygon(QPolygonF(poly),
                                        pen=QPen(labelcolor),
                                        brush=brush)
                        x, y = polygon([p.toPoint().x() for p in self.poly],
                                       [p.toPoint().y() for p in self.poly])
                    else:
                        self.addEllipse(self.poly[0].x(),
                                        self.poly[0].y(),
                                        2,
                                        2,
                                        pen=QPen(Qt.red))
                        x = self.poly[0].toPoint().x()
                        y = self.poly[0].toPoint().y()
                    self.geodata.manuallabel[y, x] = int(label[0])

            # remove the trace painted so far
            for p in self.pathset:
                self.removeItem(p)
    def draw_connection_line(painter, x1, y1, x2, y2, h1, h2):
        # Account for list view headers.
        y1 += h1
        y2 += h2

        # Invisible output ports don't get a connecting dot.
        if y1 > h1:
            painter.drawLine(x1, y1, x1 + 4, y1)

        # Setup control points
        spline = QPolygon(4)
        cp = int((x2 - x1 - 8) * 0.4)
        spline.setPoints(x1 + 4, y1, x1 + 4 + cp, y1, x2 - 4 - cp, y2, x2 - 4,
                         y2)
        # The connection line
        path = QPainterPath()
        path.moveTo(spline.at(0))
        path.cubicTo(spline.at(1), spline.at(2), spline.at(3))
        painter.strokePath(path, painter.pen())

        # painter.drawLine(x1 + 4, y1, x2 - 4, y2)

        # Invisible input ports don't get a connecting dot.
        if y2 > h2:
            painter.drawLine(x2 - 4, y2, x2, y2)
Example #26
0
    def draw_item(self, face, painter):
        is_draw = True
        if self.is_clipping:
            is_draw = self.sphere.is_face_visible(face)
        if is_draw:
            polygon = QPolygon()
            for index, point_index in enumerate(face):
                p1_x = int(self.sphere.geom.points[face[index - 1]][0])
                p1_y = int(self.sphere.geom.points[face[index - 1]][1])
                p1_z = int(self.sphere.geom.points[face[index - 1]][2])

                p2_x = int(self.sphere.geom.points[point_index][0])
                p2_y = int(self.sphere.geom.points[point_index][1])
                p2_z = int(self.sphere.geom.points[point_index][2])

                if self.sphere.projection_name == "front":
                    # Фронтальная проекция (вид спереди) -> z = 0
                    real_p1 = QPoint(p1_x, p1_y)
                    real_p2 = QPoint(p2_x, p2_y)
                elif self.sphere.projection_name == "horizontal":
                    # Горизонтальная проекция (вид сверху) -> y = 0
                    real_p1 = QPoint(p1_x, p1_z)
                    real_p2 = QPoint(p2_x, p2_z)
                elif self.sphere.projection_name == "profile":
                    # Профильная проекция (вид сбоку) -> x = 0
                    real_p1 = QPoint(p1_y, p1_z)
                    real_p2 = QPoint(p2_y, p2_z)
                else:
                    real_p1 = QPoint(p1_x, p1_y)
                    real_p2 = QPoint(p2_x, p2_y)

                # Точки для проволочного рисования
                real_p1.setX(self.width() / 2 + real_p1.x())
                real_p1.setY(self.height() / 2 - real_p1.y())
                real_p2.setX(self.width() / 2 + real_p2.x())
                real_p2.setY(self.height() / 2 - real_p2.y())

                # Полигоны для рисования с цветом
                polygon.append(real_p1)
                polygon.append(real_p2)

                if not self.is_light:
                    painter.drawLine(real_p1, real_p2)

            if self.is_light:

                painter.setBrush(
                    self.sphere.get_face_light(face, self.faces_color))
                painter.drawPolygon(polygon)
Example #27
0
def widgetQuadrant(rect, point):
    center = rect.center()

    if QPolygon([rect.topLeft(), rect.topRight(),
                 center]).containsPoint(point, 0):
        return consts.UP
    if QPolygon([rect.bottomLeft(),
                 rect.bottomRight(), center]).containsPoint(point, 0):
        return consts.DOWN
    if QPolygon([rect.topLeft(), rect.bottomLeft(),
                 center]).containsPoint(point, 0):
        return consts.LEFT
    if QPolygon([rect.bottomRight(),
                 rect.topRight(), center]).containsPoint(point, 0):
        return consts.RIGHT
    def draw_item(self, face, painter):
        is_draw = True
        if self.is_clipping:
            is_draw = self.sphere.is_face_visible(face)
        if is_draw:
            polygon = QPolygon()
            for index, point_index in enumerate(face):
                p1_x = int(self.sphere.geom.points[face[index-1]][0])
                p1_y = int(self.sphere.geom.points[face[index-1]][1])
                p1_z = int(self.sphere.geom.points[face[index-1]][2])

                p2_x = int(self.sphere.geom.points[point_index][0])
                p2_y = int(self.sphere.geom.points[point_index][1])
                p2_z = int(self.sphere.geom.points[point_index][2])

                if self.sphere.projection_name == "front":
                    # Фронтальная проекция (вид спереди) -> z = 0
                    real_p1 = QPoint(p1_x, p1_y)
                    real_p2 = QPoint(p2_x, p2_y)
                elif self.sphere.projection_name == "horizontal":
                    # Горизонтальная проекция (вид сверху) -> y = 0
                    real_p1 = QPoint(p1_x, p1_z)
                    real_p2 = QPoint(p2_x, p2_z)
                elif self.sphere.projection_name == "profile":
                    # Профильная проекция (вид сбоку) -> x = 0
                    real_p1 = QPoint(p1_y, p1_z)
                    real_p2 = QPoint(p2_y, p2_z)
                else:
                    real_p1 = QPoint(p1_x, p1_y)
                    real_p2 = QPoint(p2_x, p2_y)

                # Точки для проволочного рисования
                real_p1.setX(self.width()/2 + real_p1.x())
                real_p1.setY(self.height()/2 - real_p1.y())
                real_p2.setX(self.width()/2 + real_p2.x())
                real_p2.setY(self.height()/2 - real_p2.y())

                # Полигоны для рисования с цветом
                polygon.append(real_p1)
                polygon.append(real_p2)

                if not self.is_light:
                    painter.drawLine(real_p1, real_p2)

            if self.is_light:

                painter.setBrush(self.sphere.get_face_light(face, self.faces_color))
                painter.drawPolygon(polygon)
Example #29
0
    def paint_event_bar_vertical(qp: QPainter, index_rect: QRect,
                                 back_ground: QColor, align: int):
        if align == ALIGN_RIGHT:
            rect = index_rect
            rect.setLeft(rect.left() + 10)
            arrow_points = [
                QPoint(rect.left() - 10,
                       rect.center().y()),
                rect.topLeft(),
                rect.topRight(),
                rect.bottomRight(),
                rect.bottomLeft()
            ]
        else:
            rect = index_rect
            rect.setRight(rect.right() - 10)
            arrow_points = [
                QPoint(rect.right() + 10,
                       rect.center().y()),
                rect.bottomRight(),
                rect.bottomLeft(),
                rect.topLeft(),
                rect.topRight()
            ]

        qp.setBrush(back_ground)
        qp.drawPolygon(QPolygon(arrow_points))
Example #30
0
    def initUI(self):
        self.setGeometry(self.left, self.top, self._width, self._height)

        # Create widget
        self.label = QLabel(self)

        self.pointer = QPolygon([
            QtCore.QPoint(2, 0),
            QtCore.QPoint(-2, 0),
            QtCore.QPoint(0, -(self._sidelength / 2))
        ])

        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.update)
        timer.timeout.connect(self.showmini)
        timer.start(self.refreshrate)

        # This is the part to make the application act as an overlay

        self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
        self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.CustomizeWindowHint
                            | QtCore.Qt.FramelessWindowHint
                            | QtCore.Qt.WindowStaysOnBottomHint
                            | QtCore.Qt.SplashScreen)

        self.show()

        self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
        quitAction = QAction("Quit", self)
        quitAction.triggered.connect(sys.exit)
        self.addAction(quitAction)
 def draw_third_cond(self, qp, amount, diameter):
     target = random.randrange(0, amount)
     for i in range(amount):
         color = random.choice(self.colors)
         form = random.choice(self.forms)
         x = random.randrange(100, 1800, 20)
         y = random.randrange(100, 800, 20)
         self.forms_list.append((x, y))
         qp.setPen(Qt.SolidLine)
         if i == target:
             self.target_x = x
             self.target_y = y
             qp.setBrush(QtGui.QColor(54, 50, 168))
             qp.drawEllipse(x - diameter, y - diameter, diameter, diameter)
         else:
             qp.setBrush(QtGui.QColor(color[0], color[1], color[2]))
             if form == 'rect':
                 qp.drawRect(x - diameter, y - diameter, diameter, diameter)
             elif form == 'triangle':
                 points = [
                     QPoint(x - diameter, y - diameter),
                     QPoint(x - diameter * 2, y - diameter),
                     QPoint(x - diameter, y - diameter * 2),
                 ]
                 poly = QPolygon(points)
                 qp.drawPolygon(poly)
             elif form == 'circle':
                 qp.drawEllipse(x - diameter, y - diameter, diameter, diameter)
Example #32
0
    def draw_connection_line(self, painter, x1, y1, x2, y2, h1, h2):
        # Account for list view headers.
        y1 += h1
        y2 += h2

        # Invisible output ports don't get a connecting dot.
        if y1 > h1:
            painter.drawLine(x1, y1, x1 + 4, y1)

        # Setup control points
        spline = QPolygon(4)
        cp = int((x2 - x1 - 8) * 0.4)
        spline.setPoints(x1 + 4, y1,
                         x1 + 4 + cp, y1,
                         x2 - 4 - cp, y2,
                         x2 - 4, y2)
        # The connection line
        path = QPainterPath()
        path.moveTo(spline.at(0))
        path.cubicTo(spline.at(1), spline.at(2), spline.at(3))
        painter.strokePath(path, painter.pen())

        # painter.drawLine(x1 + 4, y1, x2 - 4, y2)

        # Invisible input ports don't get a connecting dot.
        if y2 > h2:
            painter.drawLine(x2 - 4, y2, x2, y2)
 def __grabRegion(self):
     """
     Private method to grab the selected region (i.e. do the snapshot).
     """
     pol = QPolygon(self.__selection)
     if not pol.isEmpty():
         self.__grabbing = True
         
         xOffset = self.__pixmap.rect().x() - pol.boundingRect().x()
         yOffset = self.__pixmap.rect().y() - pol.boundingRect().y()
         translatedPol = pol.translated(xOffset, yOffset)
         
         pixmap2 = QPixmap(pol.boundingRect().size())
         pixmap2.fill(Qt.transparent)
         
         pt = QPainter()
         pt.begin(pixmap2)
         if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff):
             pt.setRenderHints(
                 QPainter.Antialiasing |
                 QPainter.HighQualityAntialiasing |
                 QPainter.SmoothPixmapTransform,
                 True)
             pt.setBrush(Qt.black)
             pt.setPen(QPen(QBrush(Qt.black), 0.5))
             pt.drawPolygon(translatedPol)
             pt.setCompositionMode(QPainter.CompositionMode_SourceIn)
         else:
             pt.setClipRegion(QRegion(translatedPol))
             pt.setCompositionMode(QPainter.CompositionMode_Source)
         
         pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect())
         pt.end()
         
         self.grabbed.emit(pixmap2)
 def mousePressEvent(self, evt):
     """
     Protected method to handle mouse button presses.
     
     @param evt mouse press event (QMouseEvent)
     """
     self.__pBefore = evt.pos()
     
     self.__showHelp = not self.__helpTextRect.contains(evt.pos())
     if evt.button() == Qt.LeftButton:
         self.__mouseDown = True
         self.__dragStartPoint = evt.pos()
         self.__selectionBeforeDrag = QPolygon(self.__selection)
         if not self.__selection.containsPoint(evt.pos(), Qt.WindingFill):
             self.__newSelection = True
             self.__selection = QPolygon()
         else:
             self.setCursor(Qt.ClosedHandCursor)
     elif evt.button() == Qt.RightButton:
         self.__newSelection = False
         self.__selection = QPolygon()
         self.setCursor(Qt.CrossCursor)
     self.update()
Example #35
0
    def draw_element(self, canvas, A, B, C, material, scale):
        first = QPoint(*scale(A))
        second = QPoint(*scale(B))
        third = QPoint(*scale(C))

        element = QPolygon()
        element.append(first)
        element.append(second)
        element.append(third)
        element.append(first)
        if material == 1:
            canvas.setPen(COL_FIG)
            canvas.setBrush(QBrush(COL_FIG_INNNER))  # drawPolygon() use it
        else:
            canvas.setPen(COL_AIR)
            canvas.setBrush(QBrush(COL_AIR_INNER))
        canvas.drawPolygon(element)
Example #36
0
    def draw_mesh(self, canvas):
        """
        Divide figure and it's air-rectangles by right triangles
        """
        M = self.mesh
        scale = self.generate_scaler()
        form = self.mesh.data["form"]

        # Draw air surroundings
        canvas.setPen(self.COL_AIR)
        if M.NAT != 0:
            self.draw_rect_mesh(canvas, 0, 0, M.NAL + M.NFX + M.NAR, M.NAT)
        if M.NAB != 0:
            self.draw_rect_mesh(canvas, 0, M.NAT + M.NFY, M.NAL + M.NFX + M.NAR, M.NAB)
        if M.NAL != 0:
            self.draw_rect_mesh(canvas, 0, M.NAT, M.NAL, M.NFY)
        if M.NAR != 0:
            self.draw_rect_mesh(canvas, M.NAL + M.NFX, M.NAT, M.NAR, M.NFY)

        # Draw contour of mirrored air part
        most_left_x, most_left_y = scale(self.vertexes[0])
        most_right_x, most_right_y = scale(self.vertexes[1])
        third_x, third_y = scale(self.vertexes[2])
        if form == 0:
            canvas.drawLine(most_left_x, most_left_y, most_right_x, most_left_y)
            canvas.drawLine(most_right_x, most_right_y, most_right_x, most_left_y)
        elif form == 1:
            canvas.drawLine(most_left_x, most_right_y, most_right_x, most_right_y)
            canvas.drawLine(most_left_x, most_right_y, most_left_x, most_left_y)
        elif form == 2:
            canvas.drawLine(most_left_x, third_y, most_right_x, third_y)
            canvas.drawLine(most_right_x, most_right_y, most_right_x, third_y)
        elif form == 3:
            canvas.drawLine(most_left_x, third_y, most_right_x, third_y)
            canvas.drawLine(most_left_x, most_left_y, most_left_x, third_y)

        # Draw the figure and complete it to rectangle with air
        canvas.setPen(self.COL_FIG)
        self.draw_figure_mesh(canvas, form)

        # Fill the figure
        the_figure = QPolygon()
        for vertex in self.vertexes:
            x, y = scale(vertex)
            the_figure.append(QPoint(x, y))
        the_figure.append(the_figure.first())  # close the polygon
        canvas.setPen(self.COL_FIG)
        canvas.setBrush(QBrush(self.COL_FIG_INNNER))  # drawPolygon() use it
        canvas.drawPolygon(the_figure)
class SnapshotFreehandGrabber(QWidget):
    """
    Class implementing a grabber widget for a freehand snapshot region.
    
    @signal grabbed(QPixmap) emitted after the region was grabbed
    """
    grabbed = pyqtSignal(QPixmap)
    
    def __init__(self):
        """
        Constructor
        """
        super(SnapshotFreehandGrabber, self).__init__(
            None,
            Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint |
            Qt.FramelessWindowHint | Qt.Tool)
        
        self.__selection = QPolygon()
        self.__mouseDown = False
        self.__newSelection = False
        self.__handleSize = 10
        self.__showHelp = True
        self.__grabbing = False
        self.__dragStartPoint = QPoint()
        self.__selectionBeforeDrag = QPolygon()
        self.__locale = QLocale()
        
        self.__helpTextRect = QRect()
        self.__helpText = self.tr(
            "Select a region using the mouse. To take the snapshot,"
            " press the Enter key or double click. Press Esc to quit.")
        
        self.__pixmap = QPixmap()
        self.__pBefore = QPoint()
        
        self.setMouseTracking(True)
        
        QTimer.singleShot(200, self.__initialize)
    
    def __initialize(self):
        """
        Private slot to initialize the rest of the widget.
        """
        self.__desktop = QApplication.desktop()
        x = self.__desktop.x()
        y = self.__desktop.y()
        if qVersion() >= "5.0.0":
            self.__pixmap = QApplication.screens()[0].grabWindow(
                self.__desktop.winId(), x, y,
                self.__desktop.width(), self.__desktop.height())
        else:
            self.__pixmap = QPixmap.grabWindow(
                self.__desktop.winId(), x, y,
                self.__desktop.width(), self.__desktop.height())
        self.resize(self.__pixmap.size())
        self.move(x, y)
        self.setCursor(Qt.CrossCursor)
        self.show()

        self.grabMouse()
        self.grabKeyboard()
        self.activateWindow()
    
    def paintEvent(self, evt):
        """
        Protected method handling paint events.
        
        @param evt paint event (QPaintEvent)
        """
        if self.__grabbing:     # grabWindow() should just get the background
            return
        
        painter = QPainter(self)
        pal = QPalette(QToolTip.palette())
        font = QToolTip.font()
        
        handleColor = pal.color(QPalette.Active, QPalette.Highlight)
        handleColor.setAlpha(160)
        overlayColor = QColor(0, 0, 0, 160)
        textColor = pal.color(QPalette.Active, QPalette.Text)
        textBackgroundColor = pal.color(QPalette.Active, QPalette.Base)
        painter.drawPixmap(0, 0, self.__pixmap)
        painter.setFont(font)
        
        pol = QPolygon(self.__selection)
        if not self.__selection.boundingRect().isNull():
            # Draw outline around selection.
            # Important: the 1px-wide outline is *also* part of the
            # captured free-region
            pen = QPen(handleColor, 1, Qt.SolidLine, Qt.SquareCap,
                       Qt.BevelJoin)
            painter.setPen(pen)
            painter.drawPolygon(pol)
            
            # Draw the grey area around the selection.
            grey = QRegion(self.rect())
            grey = grey - QRegion(pol)
            painter.setClipRegion(grey)
            painter.setPen(Qt.NoPen)
            painter.setBrush(overlayColor)
            painter.drawRect(self.rect())
            painter.setClipRect(self.rect())
            drawPolygon(painter, pol, handleColor)
        
        if self.__showHelp:
            painter.setPen(textColor)
            painter.setBrush(textBackgroundColor)
            self.__helpTextRect = painter.boundingRect(
                self.rect().adjusted(2, 2, -2, -2),
                Qt.TextWordWrap, self.__helpText).translated(
                -self.__desktop.x(), -self.__desktop.y())
            self.__helpTextRect.adjust(-2, -2, 4, 2)
            drawPolygon(painter, self.__helpTextRect, textColor,
                        textBackgroundColor)
            painter.drawText(
                self.__helpTextRect.adjusted(3, 3, -3, -3),
                Qt.TextWordWrap, self.__helpText)
        
        if self.__selection.isEmpty():
            return
        
        # The grabbed region is everything which is covered by the drawn
        # rectangles (border included). This means that there is no 0px
        # selection, since a 0px wide rectangle will always be drawn as a line.
        boundingRect = self.__selection.boundingRect()
        txt = "{0}, {1} ({2} x {3})".format(
            self.__locale.toString(boundingRect.x()),
            self.__locale.toString(boundingRect.y()),
            self.__locale.toString(boundingRect.width()),
            self.__locale.toString(boundingRect.height())
        )
        textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt)
        boundingRect = textRect.adjusted(-4, 0, 0, 0)
        
        polBoundingRect = pol.boundingRect()
        if (textRect.width() <
            polBoundingRect.width() - 2 * self.__handleSize) and \
           (textRect.height() <
            polBoundingRect.height() - 2 * self.__handleSize) and \
           polBoundingRect.width() > 100 and \
           polBoundingRect.height() > 100:
            # center, unsuitable for small selections
            boundingRect.moveCenter(polBoundingRect.center())
            textRect.moveCenter(polBoundingRect.center())
        elif polBoundingRect.y() - 3 > textRect.height() and \
                polBoundingRect.x() + textRect.width() < self.rect().width():
            # on top, left aligned
            boundingRect.moveBottomLeft(
                QPoint(polBoundingRect.x(), polBoundingRect.y() - 3))
            textRect.moveBottomLeft(
                QPoint(polBoundingRect.x() + 2, polBoundingRect.y() - 3))
        elif polBoundingRect.x() - 3 > textRect.width():
            # left, top aligned
            boundingRect.moveTopRight(
                QPoint(polBoundingRect.x() - 3, polBoundingRect.y()))
            textRect.moveTopRight(
                QPoint(polBoundingRect.x() - 5, polBoundingRect.y()))
        elif (polBoundingRect.bottom() + 3 + textRect.height() <
              self.rect().bottom()) and \
                polBoundingRect.right() > textRect.width():
            # at bottom, right aligned
            boundingRect.moveTopRight(
                QPoint(polBoundingRect.right(), polBoundingRect.bottom() + 3))
            textRect.moveTopRight(
                QPoint(polBoundingRect.right() - 2,
                       polBoundingRect.bottom() + 3))
        elif polBoundingRect.right() + textRect.width() + 3 < \
                self.rect().width():
            # right, bottom aligned
            boundingRect.moveBottomLeft(
                QPoint(polBoundingRect.right() + 3, polBoundingRect.bottom()))
            textRect.moveBottomLeft(
                QPoint(polBoundingRect.right() + 5, polBoundingRect.bottom()))
        
        # If the above didn't catch it, you are running on a very
        # tiny screen...
        drawPolygon(painter, boundingRect, textColor, textBackgroundColor)
        painter.drawText(textRect, Qt.AlignHCenter, txt)
        
        if (polBoundingRect.height() > self.__handleSize * 2 and
            polBoundingRect.width() > self.__handleSize * 2) or \
           not self.__mouseDown:
            painter.setBrush(Qt.transparent)
            painter.setClipRegion(QRegion(pol))
            painter.drawPolygon(QPolygon(self.rect()))
    
    def mousePressEvent(self, evt):
        """
        Protected method to handle mouse button presses.
        
        @param evt mouse press event (QMouseEvent)
        """
        self.__pBefore = evt.pos()
        
        self.__showHelp = not self.__helpTextRect.contains(evt.pos())
        if evt.button() == Qt.LeftButton:
            self.__mouseDown = True
            self.__dragStartPoint = evt.pos()
            self.__selectionBeforeDrag = QPolygon(self.__selection)
            if not self.__selection.containsPoint(evt.pos(), Qt.WindingFill):
                self.__newSelection = True
                self.__selection = QPolygon()
            else:
                self.setCursor(Qt.ClosedHandCursor)
        elif evt.button() == Qt.RightButton:
            self.__newSelection = False
            self.__selection = QPolygon()
            self.setCursor(Qt.CrossCursor)
        self.update()
    
    def mouseMoveEvent(self, evt):
        """
        Protected method to handle mouse movements.
        
        @param evt mouse move event (QMouseEvent)
        """
        shouldShowHelp = not self.__helpTextRect.contains(evt.pos())
        if shouldShowHelp != self.__showHelp:
            self.__showHelp = shouldShowHelp
            self.update()
        
        if self.__mouseDown:
            if self.__newSelection:
                p = evt.pos()
                self.__selection.append(p)
            else:
                # moving the whole selection
                p = evt.pos() - self.__pBefore  # Offset
                self.__pBefore = evt.pos()  # save position for next iteration
                self.__selection.translate(p)
            
            self.update()
        else:
            if self.__selection.boundingRect().isEmpty():
                return
            
            if self.__selection.containsPoint(evt.pos(), Qt.WindingFill):
                self.setCursor(Qt.OpenHandCursor)
            else:
                self.setCursor(Qt.CrossCursor)
    
    def mouseReleaseEvent(self, evt):
        """
        Protected method to handle mouse button releases.
        
        @param evt mouse release event (QMouseEvent)
        """
        self.__mouseDown = False
        self.__newSelection = False
        if self.__selection.containsPoint(evt.pos(), Qt.WindingFill):
            self.setCursor(Qt.OpenHandCursor)
        self.update()
    
    def mouseDoubleClickEvent(self, evt):
        """
        Protected method to handle mouse double clicks.
        
        @param evt mouse double click event (QMouseEvent)
        """
        self.__grabRegion()
    
    def keyPressEvent(self, evt):
        """
        Protected method to handle key presses.
        
        @param evt key press event (QKeyEvent)
        """
        if evt.key() == Qt.Key_Escape:
            self.grabbed.emit(QPixmap())
        elif evt.key() in [Qt.Key_Enter, Qt.Key_Return]:
            self.__grabRegion()
        else:
            evt.ignore()
    
    def __grabRegion(self):
        """
        Private method to grab the selected region (i.e. do the snapshot).
        """
        pol = QPolygon(self.__selection)
        if not pol.isEmpty():
            self.__grabbing = True
            
            xOffset = self.__pixmap.rect().x() - pol.boundingRect().x()
            yOffset = self.__pixmap.rect().y() - pol.boundingRect().y()
            translatedPol = pol.translated(xOffset, yOffset)
            
            pixmap2 = QPixmap(pol.boundingRect().size())
            pixmap2.fill(Qt.transparent)
            
            pt = QPainter()
            pt.begin(pixmap2)
            if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff):
                pt.setRenderHints(
                    QPainter.Antialiasing |
                    QPainter.HighQualityAntialiasing |
                    QPainter.SmoothPixmapTransform,
                    True)
                pt.setBrush(Qt.black)
                pt.setPen(QPen(QBrush(Qt.black), 0.5))
                pt.drawPolygon(translatedPol)
                pt.setCompositionMode(QPainter.CompositionMode_SourceIn)
            else:
                pt.setClipRegion(QRegion(translatedPol))
                pt.setCompositionMode(QPainter.CompositionMode_Source)
            
            pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect())
            pt.end()
            
            self.grabbed.emit(pixmap2)
 def paintEvent(self, evt):
     """
     Protected method handling paint events.
     
     @param evt paint event (QPaintEvent)
     """
     if self.__grabbing:     # grabWindow() should just get the background
         return
     
     painter = QPainter(self)
     pal = QPalette(QToolTip.palette())
     font = QToolTip.font()
     
     handleColor = pal.color(QPalette.Active, QPalette.Highlight)
     handleColor.setAlpha(160)
     overlayColor = QColor(0, 0, 0, 160)
     textColor = pal.color(QPalette.Active, QPalette.Text)
     textBackgroundColor = pal.color(QPalette.Active, QPalette.Base)
     painter.drawPixmap(0, 0, self.__pixmap)
     painter.setFont(font)
     
     pol = QPolygon(self.__selection)
     if not self.__selection.boundingRect().isNull():
         # Draw outline around selection.
         # Important: the 1px-wide outline is *also* part of the
         # captured free-region
         pen = QPen(handleColor, 1, Qt.SolidLine, Qt.SquareCap,
                    Qt.BevelJoin)
         painter.setPen(pen)
         painter.drawPolygon(pol)
         
         # Draw the grey area around the selection.
         grey = QRegion(self.rect())
         grey = grey - QRegion(pol)
         painter.setClipRegion(grey)
         painter.setPen(Qt.NoPen)
         painter.setBrush(overlayColor)
         painter.drawRect(self.rect())
         painter.setClipRect(self.rect())
         drawPolygon(painter, pol, handleColor)
     
     if self.__showHelp:
         painter.setPen(textColor)
         painter.setBrush(textBackgroundColor)
         self.__helpTextRect = painter.boundingRect(
             self.rect().adjusted(2, 2, -2, -2),
             Qt.TextWordWrap, self.__helpText).translated(
             -self.__desktop.x(), -self.__desktop.y())
         self.__helpTextRect.adjust(-2, -2, 4, 2)
         drawPolygon(painter, self.__helpTextRect, textColor,
                     textBackgroundColor)
         painter.drawText(
             self.__helpTextRect.adjusted(3, 3, -3, -3),
             Qt.TextWordWrap, self.__helpText)
     
     if self.__selection.isEmpty():
         return
     
     # The grabbed region is everything which is covered by the drawn
     # rectangles (border included). This means that there is no 0px
     # selection, since a 0px wide rectangle will always be drawn as a line.
     boundingRect = self.__selection.boundingRect()
     txt = "{0}, {1} ({2} x {3})".format(
         self.__locale.toString(boundingRect.x()),
         self.__locale.toString(boundingRect.y()),
         self.__locale.toString(boundingRect.width()),
         self.__locale.toString(boundingRect.height())
     )
     textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt)
     boundingRect = textRect.adjusted(-4, 0, 0, 0)
     
     polBoundingRect = pol.boundingRect()
     if (textRect.width() <
         polBoundingRect.width() - 2 * self.__handleSize) and \
        (textRect.height() <
         polBoundingRect.height() - 2 * self.__handleSize) and \
        polBoundingRect.width() > 100 and \
        polBoundingRect.height() > 100:
         # center, unsuitable for small selections
         boundingRect.moveCenter(polBoundingRect.center())
         textRect.moveCenter(polBoundingRect.center())
     elif polBoundingRect.y() - 3 > textRect.height() and \
             polBoundingRect.x() + textRect.width() < self.rect().width():
         # on top, left aligned
         boundingRect.moveBottomLeft(
             QPoint(polBoundingRect.x(), polBoundingRect.y() - 3))
         textRect.moveBottomLeft(
             QPoint(polBoundingRect.x() + 2, polBoundingRect.y() - 3))
     elif polBoundingRect.x() - 3 > textRect.width():
         # left, top aligned
         boundingRect.moveTopRight(
             QPoint(polBoundingRect.x() - 3, polBoundingRect.y()))
         textRect.moveTopRight(
             QPoint(polBoundingRect.x() - 5, polBoundingRect.y()))
     elif (polBoundingRect.bottom() + 3 + textRect.height() <
           self.rect().bottom()) and \
             polBoundingRect.right() > textRect.width():
         # at bottom, right aligned
         boundingRect.moveTopRight(
             QPoint(polBoundingRect.right(), polBoundingRect.bottom() + 3))
         textRect.moveTopRight(
             QPoint(polBoundingRect.right() - 2,
                    polBoundingRect.bottom() + 3))
     elif polBoundingRect.right() + textRect.width() + 3 < \
             self.rect().width():
         # right, bottom aligned
         boundingRect.moveBottomLeft(
             QPoint(polBoundingRect.right() + 3, polBoundingRect.bottom()))
         textRect.moveBottomLeft(
             QPoint(polBoundingRect.right() + 5, polBoundingRect.bottom()))
     
     # If the above didn't catch it, you are running on a very
     # tiny screen...
     drawPolygon(painter, boundingRect, textColor, textBackgroundColor)
     painter.drawText(textRect, Qt.AlignHCenter, txt)
     
     if (polBoundingRect.height() > self.__handleSize * 2 and
         polBoundingRect.width() > self.__handleSize * 2) or \
        not self.__mouseDown:
         painter.setBrush(Qt.transparent)
         painter.setClipRegion(QRegion(pol))
         painter.drawPolygon(QPolygon(self.rect()))