Пример #1
0
    def create_major_ticks(self):
        """
        Painter of the major ticks
        """
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(*self.center_p())

        # painter.setPen(Qt.NoPen)
        # Major ticks color
        self.pen = QPen(QColor(0, 0, 0, 255))
        self.pen.setWidth(2)
        # # if outline_pen_with > 0:
        painter.setPen(self.pen)

        painter.rotate(self.scale_angle_start_value - self.angle_offset)
        steps_size = (float(self.scale_angle_size) /
                      float(self.scala_main_count))
        scale_line_outer_start = self.widget_diameter / 2
        scale_line_lenght = (self.widget_diameter /
                             2) - (self.widget_diameter / 20)
        # print(stepszize)
        for i in range(self.scala_main_count + 1):
            painter.drawLine(scale_line_lenght, 0, scale_line_outer_start, 0)
            painter.rotate(steps_size)
Пример #2
0
 def draw_pts(self):
     painter = QPainter(self.field)
     painter.setPen(QPen(Qt.red, 4))
     painter.translate(self.field.width() / 2, self.field.height() / 2)
     for p in self.path.poses:
         pt = QPointF(p.x, p.y)
         painter.drawPoint(pt)
Пример #3
0
 def pixmapFromSvg(self, pmapSize=None, withBorders=None):
     """returns a pixmap with default size as given in SVG and optional borders/shadows"""
     if withBorders is None:
         withBorders = Preferences.showShadows
     if withBorders:
         wantSize = self.tileset.tileSize.toSize()
     else:
         wantSize = self.tileset.faceSize.toSize()
     if not pmapSize:
         pmapSize = wantSize
     result = QPixmap(pmapSize)
     result.fill(Qt.transparent)
     painter = QPainter(result)
     if not painter.isActive():
         logException('painter is not active. Wanted size: %s' % str(pmapSize))
     try:
         xScale = float(pmapSize.width()) / wantSize.width()
         yScale = float(pmapSize.height()) / wantSize.height()
     except ZeroDivisionError:
         xScale = 1
         yScale = 1
     if not withBorders:
         painter.scale(*self.tileset.tileFaceRelation())
         painter.translate(-self.facePos())
     renderer = self.tileset.renderer()
     renderer.render(painter, self.elementId())
     painter.resetTransform()
     self._drawDarkness(painter)
     if self.showFace():
         faceSize = self.tileset.faceSize.toSize()
         faceSize = QSize(faceSize.width() * xScale, faceSize.height() * yScale)
         painter.translate(self.facePos())
         renderer.render(painter, self.tileset.svgName[self.tile.element.lower()],
                 QRectF(QPointF(), QSizeF(faceSize)))
     return result
Пример #4
0
    def make_piece_from_path(o, piece_id, qpainter_path):
        # generate the mask, and call back to actually create the piec.
        path = qpainter_path
        path.closeSubpath()
        #determine the required size of the mask
        mask_rect = path.boundingRect().toAlignedRect()
        #create the mask
        mask = QImage(mask_rect.size(), QImage.Format_ARGB32_Premultiplied)
        # fully transparent color
        mask.fill(0x00000000)

        painter = QPainter(mask)
        painter.translate(-mask_rect.topLeft())
        #we explicitly use a pen stroke in order to let the pieces overlap a bit (which reduces rendering glitches at the edges where puzzle pieces touch)
        # 1.0 still leaves the slightest trace of a glitch. but making the stroke thicker makes the plugs appear non-matching even when they belong together.
        # 2016-06-18: changed to 0.5 -- bevel looks better
        painter.setPen(QPen(Qt.black, 0.5))
        if o.outline_only:
            painter.setBrush(Qt.NoBrush)
        else:
            painter.setBrush(Qt.SolidPattern)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawPath(path)
        painter.end()

        o.add_piece_func(piece_id=piece_id,
                         mask_image=mask,
                         offset=mask_rect.topLeft())
Пример #5
0
    def create_scale_marker_values_text(self):
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        # painter.save()
        font = QFont(self.scale_fontname, self.scale_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.ScaleValueColor)
        painter.setPen(pen_shadow)

        text_radius_factor = 0.8
        text_radius = self.widget_diameter/2 * text_radius_factor

        scale_per_div = int((self.value_max - self.value_min) / self.scala_main_count)

        angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        for i in range(self.scala_main_count + 1):
            # text = str(int((self.value_max - self.value_min) / self.scala_main_count * i))
            text = str(int(self.value_min + scale_per_div * i))
            w = fm.width(text) + 1
            h = fm.height()
            painter.setFont(QFont(self.scale_fontname, self.scale_fontsize))
            angle = angle_distance * i + float(self.scale_angle_start_value - self.angle_offset)
            x = text_radius * math.cos(math.radians(angle))
            y = text_radius * math.sin(math.radians(angle))
            # print(w, h, x, y, text)
            text = [x - int(w/2), y - int(h/2), int(w), int(h), Qt.AlignCenter, text]
            painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
Пример #6
0
    def paintEvent(self, event):
        if not self.displayedWhenStopped and not self.isAnimated():
            return

        width = min(self.width(), self.height())

        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)

        outerRadius = (width-1) * 0.5
        innerRadius = (width-1) * 0.5 * 0.38

        capsuleHeight = outerRadius - innerRadius
        capsuleWidth  = capsuleHeight * 0.23 if width > 32 else capsuleHeight * 0.35
        capsuleRadius = capsuleWidth / 2

        for i in range(12):
            color = QColor(self.color)
            color.setAlphaF(float(1.0 - float(i / 12.0)))
            p.setPen(Qt.NoPen)
            p.setBrush(color)
            p.save()
            p.translate(self.rect().center())
            p.rotate(self.angle - float(i * 30.0))
            p.drawRoundedRect(-capsuleWidth * 0.5,\
                              -(innerRadius + capsuleHeight),\
                              capsuleWidth,\
                              capsuleHeight,\
                              capsuleRadius,\
                              capsuleRadius)
            p.restore()
Пример #7
0
 def paintEvent(self, event):
     """ custom paint event to draw vertical text """
     painter = QPainter(self)        
     
     # draw box around
     arc_size, line_width=10, 1
     pen = QPen(QtCore.Qt.gray)
     pen.setWidth(line_width)
     painter.setPen(pen)
     painter.drawLine(arc_size,0, self.width(), 0)
     painter.drawLine(0, arc_size,0, self.height()-arc_size)
     painter.drawLine(arc_size-5,self.height()-1,self.width(), self.height()-1)
     painter.drawArc(0,0, arc_size*2, arc_size*2, 180*16, -90*16)
     painter.drawArc(0,self.height()-arc_size*2, arc_size*2, arc_size*2, 180*16, 90*16)
     # draw box around
     #if (self.isEnabled()):
     if self.selected:  
         painter.setPen(QtCore.Qt.black)
     else:
         painter.setPen(QtCore.Qt.gray)
     painter.translate(self.width(), self.height())
     painter.rotate(270)
     painter.drawText(QtCore.QPointF(10,- self.width()/3), self.text())
     # destroy
     del painter
     
Пример #8
0
    def paintEvent(self, paint_event):
        """Paints the box"""
        painter = QPainter(self)
        rect = self.contentsRect()
        tile_count = 3
        tile_size = rect.width() / tile_count
        painter.save()
        painter.translate(rect.x(), rect.y())

        color_index = 0
        for y in range(tile_count):

            if y % 2 == 1:
                color_index = 1
            else:
                color_index = 0

            for x in range(tile_count):
                tile_rect = QRect(x * tile_size, y * tile_size, tile_size, tile_size)
                painter.fillRect(tile_rect, self.tile_colors[color_index])

                color_index += 1
                if color_index >= len(self.tile_colors):
                    color_index = 0

        painter.restore()
        painter.fillRect(rect, self.color)

        QFrame.paintEvent(self, paint_event)
Пример #9
0
def stamp_image(image, expression_str, position, feature):
    painter = QPainter(image)
    data = QgsExpression.replaceExpressionText(expression_str, feature, None)
    if not data:
        return image

    data = data.replace(r"\n", "<br>")
    style = """
    body {
        color: yellow;
    }
    """
    doc = QTextDocument()
    doc.setDefaultStyleSheet(style)
    data = "<body>{}</body>".format(data)
    doc.setHtml(data)
    point = QPointF(20, 20)

    # Wrap the text so we don't go crazy
    if doc.size().width() > 300:
        doc.setTextWidth(300)
    if position == "top-left":
        point = QPointF(20, 20)
    elif position == "top-right":
        x = image.width() - 20 - doc.size().width()
        point = QPointF(x, 20)
    elif position == "bottom-left":
        point = QPointF(20, image.height() - 20 - doc.size().height())
    elif position == "bottom-right":
        x = image.width() - 20 - doc.size().width()
        y = image.height() - 20 - doc.size().height()
        point = QPointF(x, y)
    painter.translate(point)
    doc.drawContents(painter)
    return image
Пример #10
0
    def paintEvent(self, event):
        """ custom paint event to draw vertical text """
        painter = QPainter(self)

        # draw box around
        arc_size, line_width = 10, 1
        pen = QPen(QtCore.Qt.gray)
        pen.setWidth(line_width)
        painter.setPen(pen)
        painter.drawLine(arc_size, 0, self.width(), 0)
        painter.drawLine(0, arc_size, 0, self.height() - arc_size)
        painter.drawLine(arc_size - 5,
                         self.height() - 1, self.width(),
                         self.height() - 1)
        painter.drawArc(0, 0, arc_size * 2, arc_size * 2, 180 * 16, -90 * 16)
        painter.drawArc(0,
                        self.height() - arc_size * 2, arc_size * 2,
                        arc_size * 2, 180 * 16, 90 * 16)
        # draw box around
        #if (self.isEnabled()):
        if self.selected:
            painter.setPen(QtCore.Qt.black)
        else:
            painter.setPen(QtCore.Qt.gray)
        painter.translate(self.width(), self.height())
        painter.rotate(270)
        painter.drawText(QtCore.QPointF(10, -self.width() / 3), self.text())
        # destroy
        del painter
Пример #11
0
    def draw_filled_polygon(self, outline_pen_with=0):
        if not self.scale_polygon_colors == None:
            painter_filled_polygon = QPainter(self)
            painter_filled_polygon.setRenderHint(QPainter.Antialiasing)
            # Koordinatenursprung in die Mitte der Flaeche legen
            painter_filled_polygon.translate(self.width() / 2, self.height() / 2)

            painter_filled_polygon.setPen(Qt.NoPen)

            self.pen.setWidth(outline_pen_with)
            if outline_pen_with > 0:
                painter_filled_polygon.setPen(self.pen)

            colored_scale_polygon = self.create_polygon_pie(
                ((self.widget_diameter / 2) - (self.pen.width() / 2)) * self.gauge_color_outer_radius_factor,
                (((self.widget_diameter / 2) - (self.pen.width() / 2)) * self.gauge_color_inner_radius_factor),
                self.scale_angle_start_value, self.scale_angle_size)

            gauge_rect = QRect(QPoint(0, 0), QSize(self.widget_diameter / 2 - 1, self.widget_diameter - 1))
            grad = QConicalGradient(QPointF(0, 0), - self.scale_angle_size - self.scale_angle_start_value +
                                    self.angle_offset - 1)

            # todo definition scale color as array here
            for eachcolor in self.scale_polygon_colors:
                grad.setColorAt(eachcolor[0], eachcolor[1])
            # grad.setColorAt(.00, Qt.red)
            # grad.setColorAt(.1, Qt.yellow)
            # grad.setColorAt(.15, Qt.green)
            # grad.setColorAt(1, Qt.transparent)
            painter_filled_polygon.setBrush(grad)
            # self.brush = QBrush(QColor(255, 0, 255, 255))
            # painter_filled_polygon.setBrush(self.brush)
            painter_filled_polygon.drawPolygon(colored_scale_polygon)
Пример #12
0
 def draw_border(self):
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(*self.center_p())
     painter.setPen(QPen(Qt.green, 3))
     x0, y0 = self.center_p()
     painter.drawRect(0 - x0, 0 - y0, self.width(), self.height())
Пример #13
0
    def paintEvent(self, event):

        painter = QPainter()
        painter.begin(self)

        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(Qt.NoPen))
        painter.setBrush(QBrush(self.palette().color(QPalette.Highlight)))


        num = 8

        painter.translate(self.width()/2, self.height()/2)
        painter.rotate(360.0/num * (self.counter % num))

        for i in range(num):
            s = 25 + i

            x =  50 * math.cos(2.0 * math.pi * i / num) - s/2.0
            y =  50 * math.sin(2.0 * math.pi * i / num) - s/2.0


            painter.drawEllipse(
                x,
                y,
                s, s)
        painter.end()
Пример #14
0
    def paintEvent(self, paint_event):
        """Paints the box"""
        painter = QPainter(self)
        rect = self.contentsRect()
        tile_count = 3
        tile_size = rect.width() / tile_count
        painter.save()
        painter.translate(rect.x(), rect.y())

        color_index = 0
        for y in range(tile_count):

            if y % 2 == 1:
                color_index = 1
            else:
                color_index = 0

            for x in range(tile_count):
                tile_rect = QRect(x * tile_size, y * tile_size, tile_size,
                                  tile_size)
                painter.fillRect(tile_rect, self.tile_colors[color_index])

                color_index += 1
                if color_index >= len(self.tile_colors):
                    color_index = 0

        painter.restore()
        painter.fillRect(rect, self.color)

        QFrame.paintEvent(self, paint_event)
Пример #15
0
    def paintEvent(self, event) :

        painter = QPainter(self.viewport())
        painter.translate(-self.horizontalScrollBar().value() * self.font_width, 0)
        word_count = 0

        #// pixel offset of self row
        row = 0
        chars_per_row = self.bytesPerRow()
        #// current actual offset (in bytes)
        offset = self.verticalScrollBar().value() * chars_per_row

        if(self.origin != 0) :
            if(offset > 0) :
                offset += self.origin
                offset -= chars_per_row
            else :
                self.origin = 0
                self.updateScrollbars()

        data_size     = self.dataSize()
        widget_height = self.height()

        while(row + self.font_height < widget_height ) and (offset < data_size) :
            row_data = self.data[offset:chars_per_row+offset]
            if( row_data is not None ) : # != '' ?
                if(self.show_address) :
                    address_rva = self.address_offset + offset
                    addressBuffer = self.formatAddress(address_rva)
                    painter.setPen(QPen(self.address_color))
                    painter.drawText(0, row, len(addressBuffer) * (self.font_width+1), self.font_height, Qt.AlignTop, addressBuffer)

                painter.setPen(QPen(Qt.black))
                if(self.show_hex) :
                    self.drawHexDump(painter, offset, row, data_size, word_count, row_data)
                if(self.show_ascii) :
                    self.drawAsciiDump(painter, offset, row, data_size, row_data)
                #if(self.show_comments and self.comment_server) :
                #    self.drawComments(painter, offset, row, data_size)
            offset += chars_per_row
            row += self.font_height

        painter.setPen(QPen(self.palette().shadow().color()))

        if(self.show_address and self.show_line1) :
            line1_x = self.line1()
            painter.drawLine(line1_x, 0, line1_x, widget_height)

        if(self.show_hex    and    self.show_line2) :
            line2_x = self.line2()
            painter.drawLine(line2_x, 0, line2_x, widget_height)

        if(self.show_ascii    and    self.show_line3) :
            line3_x = self.line3()
            painter.drawLine(line3_x, 0, line3_x, widget_height)

        return
Пример #16
0
    def paintEvent(self, event):
        painter = QPainter(self)
        rect = self.geometry()
        text_rect = QRect(0, 0, rect.width(), rect.height())

        painter.translate(text_rect.bottomLeft())
        painter.rotate(-90)
        painter.drawText(QRect(QPoint(0, 0), QSize(rect.height(), rect.width())), Qt.AlignCenter, self.text())
        painter.end()
Пример #17
0
    def draw_ball(self):
        painter = QPainter(self.field)
        painter.translate(self.field.width() / 2, self.field.height() / 2)
        ball = self.config.ball

        if ball is not None:
            painter.setPen(QPen(QColor(255, 165, 0), 1))
            painter.setBrush(QColor(255, 165, 0))
            painter.drawEllipse(ball.x, ball.y, 4, 4)
Пример #18
0
    def paintEvent(self, event) :

        painter = QPainter(self.viewport())
        painter.translate(-self.horizontalScrollBar().value() * self.font_width, 0)
        word_count = 0

        #// pixel offset of self row
        row = 0
        chars_per_row = self.bytesPerRow()
        #// current actual offset (in bytes)
        offset = self.verticalScrollBar().value() * chars_per_row

        if(self.origin != 0) :
            if(offset > 0) :
                offset += self.origin
                offset -= chars_per_row
            else :
                self.origin = 0
                self.updateScrollbars()

        data_size     = self.dataSize()
        widget_height = self.height()

        while(row + self.font_height < widget_height ) and (offset < data_size) :
            row_data = self.data[offset:chars_per_row+offset]
            if( row_data is not None ) : # != '' ?
                if(self.show_address) :
                    address_rva = self.address_offset + offset
                    addressBuffer = self.formatAddress(address_rva)
                    painter.setPen(QPen(self.address_color))
                    painter.drawText(0, row, len(addressBuffer) * (self.font_width+1), self.font_height, Qt.AlignTop, addressBuffer)

                painter.setPen(QPen(Qt.black))
                if(self.show_hex) :
                    self.drawHexDump(painter, offset, row, data_size, word_count, row_data)
                if(self.show_ascii) :
                    self.drawAsciiDump(painter, offset, row, data_size, row_data)
                #if(self.show_comments and self.comment_server) :
                #    self.drawComments(painter, offset, row, data_size)
            offset += chars_per_row
            row += self.font_height

        painter.setPen(QPen(self.palette().shadow().color()))

        if(self.show_address and self.show_line1) :
            line1_x = self.line1()
            painter.drawLine(line1_x, 0, line1_x, widget_height)

        if(self.show_hex    and    self.show_line2) :
            line2_x = self.line2()
            painter.drawLine(line2_x, 0, line2_x, widget_height)

        if(self.show_ascii    and    self.show_line3) :
            line3_x = self.line3()
            painter.drawLine(line3_x, 0, line3_x, widget_height)

        return
Пример #19
0
 def update(self):
     painter = QPainter(self)#CApplication.getTelaPrincipal())
     painter.translate(self.getPos())
     self.paint(painter)
     painter.end()
     
     if not CApplication.updateRequested():
         CApplication.setUpdateRequested(True)
         QCoreApplication.postEvent(CApplication.getInstance(), EventoUpdateConsole(EventoUpdateConsole.UpdateRequest))
         return
Пример #20
0
    def drawPatchQt(self, pos, turn, invert, patch_type, image, size,
                    foreColor, backColor, penwidth):  # pylint: disable=unused-argument
        """
        :param size: patch size
        """
        path = self.PATH_SET[patch_type]
        if not path:
            # blank patch
            invert = not invert
            path = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)]

        polygon = QPolygonF([QPointF(x * size, y * size) for x, y in path])

        rot = turn % 4
        rect = [
            QPointF(0., 0.),
            QPointF(size, 0.),
            QPointF(size, size),
            QPointF(0., size)
        ]
        rotation = [0, 90, 180, 270]

        nopen = QtGui.QPen(foreColor, Qt.NoPen)
        foreBrush = QtGui.QBrush(foreColor, Qt.SolidPattern)
        if penwidth > 0:
            pen_color = QtGui.QColor(255, 255, 255)
            pen = QtGui.QPen(pen_color, Qt.SolidPattern)
            pen.setWidth(penwidth)

        painter = QPainter()
        painter.begin(image)
        painter.setPen(nopen)

        painter.translate(pos[0] * size + penwidth / 2,
                          pos[1] * size + penwidth / 2)
        painter.translate(rect[rot])
        painter.rotate(rotation[rot])

        if invert:
            # subtract the actual polygon from a rectangle to invert it
            poly_rect = QPolygonF(rect)
            polygon = poly_rect.subtracted(polygon)
        painter.setBrush(foreBrush)
        if penwidth > 0:
            # draw the borders
            painter.setPen(pen)
            painter.drawPolygon(polygon, Qt.WindingFill)
        # draw the fill
        painter.setPen(nopen)
        painter.drawPolygon(polygon, Qt.WindingFill)

        painter.end()

        return image
Пример #21
0
    def paintEvent(self, event):
        painter = QPainter(self)
        rect = self.geometry()
        text_rect = QRect(0, 0, rect.width(), rect.height())

        painter.translate(text_rect.bottomLeft())
        painter.rotate(-90)
        painter.drawText(
            QRect(QPoint(0, 0), QSize(rect.height(), rect.width())),
            Qt.AlignCenter, self.text())
        painter.end()
Пример #22
0
    def draw_big_needle_center_point(self, diameter=30):
        painter = QPainter(self)
        # painter.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        painter.setPen(Qt.NoPen)
        # painter.setPen(Qt.NoPen)
        painter.setBrush(self.CenterPointColor)
        # diameter = diameter # self.widget_diameter/6
        painter.drawEllipse(int(-diameter / 2), int(-diameter / 2), int(diameter), int(diameter))
Пример #23
0
    def draw_needle(self):
        painter = QPainter(self)
        # painter.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)
        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        painter.setPen(Qt.NoPen)
        painter.setBrush(self.NeedleColor)
        painter.rotate(((self.value - self.value_offset - self.value_min) * self.scale_angle_size /
                        (self.value_max - self.value_min)) + 90 + self.scale_angle_start_value)

        painter.drawConvexPolygon(self.value_needle[0])
Пример #24
0
    def draw_robots(self):
        painter = QPainter(self.field)
        painter.translate(self.field.width() / 2, self.field.height() / 2)

        for r in self.config.robots_yellow:
            painter.setPen(QPen(Qt.yellow, 1))
            painter.setBrush(Qt.yellow)
            painter.drawEllipse(r.pose.x, r.pose.y, 15, 15)

        for r in self.config.robots_blue:
            painter.setPen(QPen(Qt.blue, 1))
            painter.setBrush(Qt.blue)
            painter.drawEllipse(r.pose.x, r.pose.y, 15, 15)
Пример #25
0
 def paintEvent(self, event):
 
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setBrush(QBrush(QColor(192, 192, 255)))
     painter.drawRect(event.rect())
     
     painter.translate(self.width()/2.0, self.height()/2.0)
     painter.scale(self.width()*0.75/100.0, self.height()*0.75/100.0)
     painter.setBrush(QBrush(self.gradient))
     painter.drawPath(self.path)
     painter.end()
Пример #26
0
 def paintEvent(self, event):
     """Paint the widget."""
     opt = QStyleOption()
     opt.initFrom(self)
     painter = QPainter(self)
     if self._direction == QArrow.UP:
         primitive = QStyle.PE_IndicatorArrowUp
     elif self._direction == QArrow.DOWN:
         primitive = QStyle.PE_IndicatorArrowDown
     elif self._direction == QArrow.LEFT:
         primitive = QStyle.PE_IndicatorArrowLeft
     else:
         primitive = QStyle.PE_IndicatorArrowRight
     painter.translate(-5, 0)
     painter.setViewTransformEnabled(True)
     self.style().drawPrimitive(primitive, opt, painter, self)
Пример #27
0
 def paintEvent(self, event):
     """Paint the widget."""
     opt = QStyleOption()
     opt.initFrom(self)
     painter = QPainter(self)
     if self._direction == QArrow.UP:
         primitive = QStyle.PE_IndicatorArrowUp
     elif self._direction == QArrow.DOWN:
         primitive = QStyle.PE_IndicatorArrowDown
     elif self._direction == QArrow.LEFT:
         primitive = QStyle.PE_IndicatorArrowLeft
     else:
         primitive = QStyle.PE_IndicatorArrowRight
     painter.translate(-5, 0)
     painter.setViewTransformEnabled(True)
     self.style().drawPrimitive(primitive, opt, painter, self)
Пример #28
0
    def create_fine_scaled_marker(self):
        #  Description_dict = 0
        my_painter = QPainter(self)

        my_painter.setRenderHint(QPainter.Antialiasing)
        # Koordinatenursprung in die Mitte der Flaeche legen
        my_painter.translate(self.width() / 2, self.height() / 2)

        my_painter.setPen(Qt.black)
        my_painter.rotate(self.scale_angle_start_value - self.angle_offset)
        steps_size = (float(self.scale_angle_size) / float(self.scala_main_count * self.scala_subdiv_count))
        scale_line_outer_start = self.widget_diameter/2
        scale_line_lenght = (self.widget_diameter / 2) - (self.widget_diameter / 25)
        for i in range((self.scala_main_count * self.scala_subdiv_count)+1):
            my_painter.drawLine(scale_line_lenght, 0, scale_line_outer_start, 0)
            my_painter.rotate(steps_size)
Пример #29
0
    def render(self,fname):
      contentsSize = self.contentFrame.contentsSize()
      contentsSize -= QSize(self.m_scrollPosition.x(), self.m_scrollPosition.y())
      frameRect = QRect(QPoint(0, 0), contentsSize)
      #if not self.m_clipRect.isEmpty():
      #    frameRect = self.m_clipRect

      viewportSize = self.contentPage.viewportSize()
      self.contentPage.setViewportSize(contentsSize)

      image = QImage(frameRect.size(), QImage.Format_ARGB32)
      image.fill(qRgba(255, 255, 255, 0))

      painter = QPainter()

      # We use tiling approach to work-around Qt software rasterizer bug
      # when dealing with very large paint device.
      # See http://code.google.com/p/phantomjs/issues/detail?id=54.
      tileSize = 4096
      htiles = (image.width() + tileSize - 1) / tileSize
      vtiles = (image.height() + tileSize - 1) / tileSize
      for x in range(htiles):
          for y in range(vtiles):
              tileBuffer = QImage(tileSize, tileSize, QImage.Format_ARGB32)
              tileBuffer.fill(qRgba(255, 255, 255, 0))

              # Render the web page onto the small tile first
              painter.begin(tileBuffer)
              painter.setRenderHint(QPainter.Antialiasing, True)
              painter.setRenderHint(QPainter.TextAntialiasing, True)
              painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
              painter.translate(-frameRect.left(), -frameRect.top())
              painter.translate(-x * tileSize, -y * tileSize)
              self.contentFrame.render(painter, QRegion(frameRect))
              painter.end()

              # Copy the tile to the main buffer
              painter.begin(image)
              painter.setCompositionMode(QPainter.CompositionMode_Source)
              painter.drawImage(x * tileSize, y * tileSize, tileBuffer)
              painter.end()

      self.contentPage.setViewportSize(viewportSize)

      image.save(fname)

      return True
Пример #30
0
    def create_digital_indicator(self):
        """ Main value indicator inside the Gauge """
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        # Place the coordinate origin in the center
        painter.translate(*self.center_p())
        # painter.save()
        # xShadow = 3.0
        # yShadow = 3.0
        font = QFont(self.value_fontname, self.value_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.DisplayValueColor)
        painter.setPen(pen_shadow)

        text_radius = self.widget_diameter / 2 * self.text_radius_factor

        # angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        # for i in range(self.scala_main_count + 1):
        text = str(int(self.value))
        w = fm.width(text) + 1
        h = fm.height()
        painter.setFont(QFont(self.value_fontname, self.value_fontsize))

        # Mitte zwischen Skalenstart und Skalenende:
        # Skalenende = Skalenanfang - 360 + Skalenlaenge
        # Skalenmitte = (Skalenende - Skalenanfang) / 2 + Skalenanfang
        angle_end = float(self.scale_angle_start_value +
                          self.scale_angle_size - 360)
        angle = (angle_end - self.scale_angle_start_value
                 ) / 2 + self.scale_angle_start_value

        x = text_radius * math.cos(math.radians(angle))
        y = text_radius * math.sin(math.radians(angle))
        # print(w, h, x, y, text)
        text = [
            x - int(w / 2), y - int(h / 2),
            int(w),
            int(h), Qt.AlignCenter, text
        ]
        painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
Пример #31
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     qp.translate(self.width()/2, self.height()/2);
     for i in range(24):
         qp.drawLine(88, 0, 96, 0);
         qp.rotate(15.0);
         
     qp.rotate(((self.count % 24)*15+270)%360)
     qp.drawLine(50, 0, 80, 0)
     
     if self.pressed:
         qp.setBrush(QBrush(Qt.red))
         
     qp.drawEllipse(-50, -50, 100, 100)
     
     qp.end()
Пример #32
0
    def create_minor_ticks(self):
        #  Description_dict = 0
        painter = QPainter(self)

        painter.setRenderHint(QPainter.Antialiasing)
        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(*self.center_p())

        painter.setPen(Qt.black)
        painter.rotate(self.scale_angle_start_value - self.angle_offset)
        steps_size = (float(self.scale_angle_size) /
                      float(self.scala_main_count * self.scala_subdiv_count))
        scale_line_outer_start = self.widget_diameter / 2
        scale_line_lenght = (self.widget_diameter /
                             2) - (self.widget_diameter / 40)
        for i in range((self.scala_main_count * self.scala_subdiv_count) + 1):
            painter.drawLine(scale_line_lenght, 0, scale_line_outer_start, 0)
            painter.rotate(steps_size)
Пример #33
0
    def paintEvent(self, e):
        time = QTime.currentTime()
        qp = QPainter()

        qp.begin(self)
        #qp.setRenderHint(QPainter.Antialiasing)  # 开启这个抗锯齿,会很占cpu的!
        qp.translate(self.width() / 2, self.height() / 2)
        qp.scale(self.side / 200.0, self.side / 200.0)

        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.hourColor)
        qp.save()
        qp.rotate(30.0 * ((time.hour() + time.minute() / 60.0)))
        qp.drawConvexPolygon(self.hourHand)
        qp.restore()

        qp.setPen(self.hourColor)
        for i in range(12):
            qp.drawLine(88, 0, 96, 0)
            qp.rotate(30.0)

        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.minuteColor)
        qp.save()

        qp.rotate(6.0 * ((time.minute() +
                          (time.second() + time.msec() / 1000.0) / 60.0)))
        qp.drawConvexPolygon(self.minuteHand)
        qp.restore()

        qp.setPen(self.minuteColor)
        for i in range(60):
            if (i % 5) is not 0:
                qp.drawLine(92, 0, 96, 0)
            qp.rotate(6.0)

        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.secondColor)
        qp.save()
        qp.rotate(6.0 * (time.second() + time.msec() / 1000.0))
        qp.drawConvexPolygon(self.secondHand)

        qp.restore()
        qp.end()
Пример #34
0
    def renderImage(self):
        contentsSize = self.m_mainFrame.contentsSize()
        contentsSize -= QSize(self.m_scrollPosition.x(), self.m_scrollPosition.y())
        frameRect = QRect(QPoint(0, 0), contentsSize)
        if not self.m_clipRect.isEmpty():
            frameRect = self.m_clipRect

        viewportSize = self.m_webPage.viewportSize()
        self.m_webPage.setViewportSize(contentsSize)

        image = QImage(frameRect.size(), QImage.Format_ARGB32)
        image.fill(qRgba(255, 255, 255, 0))

        painter = QPainter()

        # We use tiling approach to work-around Qt software rasterizer bug
        # when dealing with very large paint device.
        # See http://code.google.com/p/phantomjs/issues/detail?id=54.
        tileSize = 4096
        htiles = (image.width() + tileSize - 1) / tileSize
        vtiles = (image.height() + tileSize - 1) / tileSize
        for x in range(htiles):
            for y in range(vtiles):
                tileBuffer = QImage(tileSize, tileSize, QImage.Format_ARGB32)
                tileBuffer.fill(qRgba(255, 255, 255, 0))

                # Render the web page onto the small tile first
                painter.begin(tileBuffer)
                painter.setRenderHint(QPainter.Antialiasing, True)
                painter.setRenderHint(QPainter.TextAntialiasing, True)
                painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
                painter.translate(-frameRect.left(), -frameRect.top())
                painter.translate(-x * tileSize, -y * tileSize)
                self.m_mainFrame.render(painter, QRegion(frameRect))
                painter.end()

                # Copy the tile to the main buffer
                painter.begin(image)
                painter.setCompositionMode(QPainter.CompositionMode_Source)
                painter.drawImage(x * tileSize, y * tileSize, tileBuffer)
                painter.end()

        self.m_webPage.setViewportSize(viewportSize)
        return image
Пример #35
0
    def paintEvent(self, event):
        realSize = min(self.width(), self.height())

        painter = QPainter()
        painter.begin(self)
        pen = QPen(Qt.black)
        pen.setWidth(1)
        painter.setPen(Qt.black)

        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(
            float(realSize) / self.scaledSize,
            float(realSize) / self.scaledSize)
        gradient = QRadialGradient(QPointF(-500, -500), 1500,
                                   QPointF(-500, -500))
        gradient.setColorAt(0, QColor(224, 224, 224))
        gradient.setColorAt(1, QColor(28, 28, 28))
        painter.setPen(pen)
        painter.setBrush(QBrush(gradient))
        painter.drawEllipse(QPointF(0, 0), 500, 500)

        gradient = QRadialGradient(QPointF(500, 500), 1500, QPointF(500, 500))
        gradient.setColorAt(0, QColor(224, 224, 224))
        gradient.setColorAt(1, QColor(28, 28, 28))
        painter.setPen(pen)
        painter.setBrush(QBrush(gradient))
        painter.drawEllipse(QPointF(0, 0), 450, 450)

        painter.setPen(pen)
        if (self.isChecked()):
            gradient = QRadialGradient(QPointF(-500, -500), 1500,
                                       QPointF(-500, -500))
            gradient.setColorAt(0, self._onColor1)
            gradient.setColorAt(1, self._onColor2)
        else:
            gradient = QRadialGradient(QPointF(500, 500), 1500,
                                       QPointF(500, 500))
            gradient.setColorAt(0, self._offColor1)
            gradient.setColorAt(1, self._offColor2)

        painter.setBrush(gradient)
        painter.drawEllipse(QPointF(0, 0), 400, 400)
        painter.end()
Пример #36
0
    def paintEvent(self, e): 
        time = QTime.currentTime() 
        qp = QPainter()

        qp.begin(self)
        #qp.setRenderHint(QPainter.Antialiasing)  # 开启这个抗锯齿,会很占cpu的!
        qp.translate(self.width() / 2, self.height() / 2) 
        qp.scale(self.side / 200.0, self.side / 200.0)
 
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.hourColor)
        qp.save()
        qp.rotate(30.0 * ((time.hour() + time.minute()/ 60.0)))
        qp.drawConvexPolygon(self.hourHand)
        qp.restore()
        
        qp.setPen(self.hourColor)
        for i in range(12): 
            qp.drawLine(88, 0, 96, 0)
            qp.rotate(30.0) 
        
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.minuteColor)
        qp.save()
        
        qp.rotate(6.0 * ((time.minute() + (time.second()+time.msec()/1000.0) / 60.0)))
        qp.drawConvexPolygon(self.minuteHand)
        qp.restore()
        
        
        qp.setPen(self.minuteColor)
        for i in range(60): 
            if (i % 5) is not 0:
                qp.drawLine(92, 0, 96, 0)
            qp.rotate(6.0) 
        
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.secondColor)
        qp.save()
        qp.rotate(6.0*(time.second()+time.msec()/1000.0))
        qp.drawConvexPolygon(self.secondHand)

        qp.restore() 
        qp.end() 
Пример #37
0
    def paintEvent(self, paint_event):
        """Paints the box"""
        painter = QPainter(self)
        rect = self.contentsRect()
        tile_count = 3
        tile_size = rect.width() / tile_count
        painter.save()
        painter.translate(rect.x(), rect.y())

        for y in range(tile_count):
            for x in range(tile_count):
                color_index = (y * tile_count + x) % 2
                tile_rect = QRect(x * tile_size, y * tile_size, tile_size, tile_size)
                painter.fillRect(tile_rect, self._tile_colors[color_index])

        painter.restore()
        painter.fillRect(rect, self._color)

        QFrame.paintEvent(self, paint_event)
Пример #38
0
 def genWINDPIXMAPS():
     """prepare wind tiles"""
     tileset = Tileset(Preferences.windTilesetName)
     for wind in WINDS:
         for prevailing in False, True:
             pwind = PlayerWind(wind, tileset, prevailing)
             pMap = QPixmap(40, 40)
             pMap.fill(Qt.transparent)
             painter = QPainter(pMap)
             painter.setRenderHint(QPainter.Antialiasing)
             painter.scale(0.40, 0.40)
             pwind.paint(painter, QStyleOptionGraphicsItem())
             for child in pwind.childItems():
                 if isinstance(child, QGraphicsSvgItem):
                     painter.save()
                     painter.translate(child.mapToParent(0.0, 0.0))
                     child.paint(painter, QStyleOptionGraphicsItem())
                     painter.restore()
             WINDPIXMAPS[(wind, prevailing)] = pMap
Пример #39
0
 def genWINDPIXMAPS():
     """prepare wind tiles"""
     tileset = Tileset(common.PREF.windTilesetName)
     for wind in WINDS:
         for prevailing in False, True:
             pwind = PlayerWind(wind, tileset, prevailing)
             pMap = QPixmap(40, 40)
             pMap.fill(Qt.transparent)
             painter = QPainter(pMap)
             painter.setRenderHint(QPainter.Antialiasing)
             painter.scale(0.40, 0.40)
             pwind.paint(painter, QStyleOptionGraphicsItem())
             for child in pwind.childItems():
                 if isinstance(child, QGraphicsSvgItem):
                     painter.save()
                     painter.translate(child.mapToParent(0.0, 0.0))
                     child.paint(painter, QStyleOptionGraphicsItem())
                     painter.restore()
             WINDPIXMAPS[(wind, prevailing)] = pMap
Пример #40
0
    def draw_big_scaled_markter(self):
        my_painter = QPainter(self)
        my_painter.setRenderHint(QPainter.Antialiasing)
        # Koordinatenursprung in die Mitte der Flaeche legen
        my_painter.translate(self.width() / 2, self.height() / 2)

        # my_painter.setPen(Qt.NoPen)
        self.pen = QPen(QColor(0, 0, 0, 255))
        self.pen.setWidth(2)
        # # if outline_pen_with > 0:
        my_painter.setPen(self.pen)

        my_painter.rotate(self.scale_angle_start_value - self.angle_offset)
        steps_size = (float(self.scale_angle_size) / float(self.scala_main_count))
        scale_line_outer_start = self.widget_diameter/2
        scale_line_lenght = (self.widget_diameter / 2) - (self.widget_diameter / 20)
        # print(stepszize)
        for i in range(self.scala_main_count+1):
            my_painter.drawLine(scale_line_lenght, 0, scale_line_outer_start, 0)
            my_painter.rotate(steps_size)
Пример #41
0
 def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile):
     """fill last meld combo with prepared content"""
     winner = self.game.winner
     faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5
     faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5
     restoredIdx = None
     for meld in winnerMelds:
         pixMap = QPixmap(faceWidth * len(meld), faceHeight)
         pixMap.fill(Qt.transparent)
         self.__meldPixMaps.append(pixMap)
         painter = QPainter(pixMap)
         for element in meld.pairs:
             painter.drawPixmap(0, 0,
                 winner.handBoard.tilesByElement(element) \
                 [0].graphics.pixmapFromSvg(QSize(faceWidth, faceHeight), withBorders=False))
             painter.translate(QPointF(faceWidth, 0.0))
         self.cbLastMeld.addItem(QIcon(pixMap), '', QVariant(meld.joined))
         if indexedMeld == meld.joined:
             restoredIdx = self.cbLastMeld.count() - 1
     if not restoredIdx and indexedMeld:
         # try again, maybe the meld changed between concealed and exposed
         indexedMeld = indexedMeld.lower()
         for idx in range(self.cbLastMeld.count()):
             meldContent = str(self.cbLastMeld.itemData(idx).toPyObject())
             if indexedMeld == meldContent.lower():
                 restoredIdx = idx
                 if lastTile not in meldContent:
                     if lastTile.lower() == lastTile:
                         lastTile = lastTile.capitalize()
                     else:
                         lastTile = lastTile.lower()
                     assert lastTile in meldContent
                     self.cbLastTile.blockSignals(True) # we want to continue right here
                     idx = self.cbLastTile.findData(QVariant(lastTile))
                     self.cbLastTile.setCurrentIndex(idx)
                     self.cbLastTile.blockSignals(False)
                 break
     if not restoredIdx:
         restoredIdx = 0
     self.cbLastMeld.setCurrentIndex(restoredIdx)
     self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight))
Пример #42
0
    def draw_needle(self):
        painter = QPainter(self)
        # painter.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)
        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        painter.setPen(Qt.NoPen)
        painter.setBrush(self.NeedleColor)
        # painter.rotate(((self.value - self.value_offset - self.value_min) * self.scale_angle_size /
        #                 (self.value_max - self.value_min)) + 90 + self.scale_angle_start_value)
        frac, whole = math.modf(self.value)
        if frac >= 0:
            frac = 1-frac
            rotFraction = ((self.value - self.value_offset - self.value_min)/(self.value_max - self.value_min))
        else:
            frac = 1+frac
            rotFraction = (((whole-frac) - self.value_offset - self.value_min)/(self.value_max - self.value_min))
        painter.rotate((1-rotFraction) * self.scale_angle_size + 90 + self.scale_angle_start_value)


        painter.drawConvexPolygon(self.value_needle[0])
Пример #43
0
 def printout(self):
     # Page width, page height, widget width
     pw = self._printer.pageRect().width()
     ph = self._printer.pageRect().height()
     ww = self._ComparingProfile.width()
     painter = QPainter(self._printer)
     scale = (ww / pw) * 1.5
     painter.scale(scale, scale)
     self._ReactionsWindow.currentWidget().render(painter)
     painter.translate(0, ph/2)
     self._ComparingProfile.render(painter)
     painter.translate(pw * 0.6, -ph/2)
     painter.scale(0.8, 0.8)
     self._ReactionsWindow.currentWidget().PrintGraph(painter, "Concentration")
     painter.translate(0, ph*0.25)
     self._ReactionsWindow.currentWidget().PrintGraph(painter, "Rate")
     painter.translate(0, ph * 0.4)
     self._ComparingProfile.PrintGraph(painter, "Concentration")
     painter.translate(0, ph * 0.25)
     self._ComparingProfile.PrintGraph(painter, "Rate")
     painter.end()
Пример #44
0
    def create_values_text(self):
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        # painter.save()
        # xShadow = 3.0
        # yShadow = 3.0
        font = QFont(self.value_fontname, self.value_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.DisplayValueColor)
        painter.setPen(pen_shadow)

        text_radius = self.widget_diameter / 2 * self.text_radius_factor

        # angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        # for i in range(self.scala_main_count + 1):
        frac, whole = math.modf(self.value)

        text = ("%0.1f" % (abs(frac)*10)) + 'E' + str(int(whole)) + ' ' + self.units
        w = fm.width(text) + 1
        h = fm.height()
        painter.setFont(QFont(self.value_fontname, self.value_fontsize))

        # Mitte zwischen Skalenstart und Skalenende:
        # Skalenende = Skalenanfang - 360 + Skalenlaenge
        # Skalenmitte = (Skalenende - Skalenanfang) / 2 + Skalenanfang
        angle_end = float(self.scale_angle_start_value + self.scale_angle_size - 360)
        angle = (angle_end - self.scale_angle_start_value) / 2 + self.scale_angle_start_value

        x = text_radius * math.cos(math.radians(angle))
        y = text_radius * math.sin(math.radians(angle))
        # print(w, h, x, y, text)
        text = [x - int(w/2), y - int(h/2), int(w), int(h), Qt.AlignCenter, text]
        painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
Пример #45
0
    def paintEvent(self, event):
        painter=QPainter(self) 
        angleSpan = self.m_endAngle - self.m_startAngle
        valueSpan = self.m_maximum - self.m_minimum
        rotate = (self.m_value - self.m_minimum) / valueSpan * angleSpan + self.m_startAngle

        targetRect = self.availableRect(self.m_backgroundRenderer)
        painter.translate((self.width() - targetRect.width()) / 2.0, (self.height() - targetRect.height()) / 2.0)
        painter.save()

        self.m_backgroundRenderer.render(painter, targetRect)

        targetRect = self.availableRect(self.m_needleRenderer)
        targetRect.moveTopLeft(QPointF(-targetRect.width() * self.m_originX,
                                  -targetRect.height() * self.m_originY))

        painter.translate(targetRect.width() * self.m_originX,
                      targetRect.height() * self.m_originY)

        painter.save()
        painter.translate(2, 4)
        painter.rotate(rotate)
        self.m_needleShadowRenderer.render(painter, targetRect)

        painter.restore()
        painter.rotate(rotate)
        self.m_needleRenderer.render(painter, targetRect)

        painter.restore();
        if self.m_showOverlay:
            targetRect = self.availableRect(self.m_overlayRenderer)
            self.m_overlayRenderer.render(painter, targetRect)
Пример #46
0
    def mouseMoveEvent(self, event):
        drag = QDrag(event.widget())
        data = QMimeData()
        data.setText(self.commit.name())

        drag.setMimeData(data)

        #data.setColorData(GREEN)
        pixmap = QPixmap(COMMIT_WIDTH, COMMIT_HEIGHT)
        pixmap.fill(WHITE)
        painter = QPainter(pixmap)
        painter.translate(0, 0)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(self.color))
        painter.drawPath(self.setup_display(0, 0))
        painter.end()

        pixmap.setMask(pixmap.createHeuristicMask())
        drag.setPixmap(pixmap)
        drag.setHotSpot(QPoint(0, 0))
        drag.start()
Пример #47
0
    def render(self, fileName):
        fileInfo = QFileInfo(fileName)
        path = QDir()
        path.mkpath(fileInfo.absolutePath())

        if fileName.lower().endswith('.pdf'):
            return self.renderPdf(fileName)

        viewportSize = QSize(self.m_page.viewportSize())
        pageSize = QSize(self.m_page.mainFrame().contentsSize())

        bufferSize = QSize()
        if not self.m_clipRect.isEmpty():
            bufferSize = self.m_clipRect.size()
        else:
            bufferSize = self.m_page.mainFrame().contentsSize()

        if pageSize == '':
            return False

        image = QImage(bufferSize, QImage.Format_ARGB32)
        image.fill(qRgba(255, 255, 255, 0))
        p = QPainter(image)

        p.setRenderHint(QPainter.Antialiasing, True)
        p.setRenderHint(QPainter.TextAntialiasing, True)
        p.setRenderHint(QPainter.SmoothPixmapTransform, True)

        self.m_page.setViewportSize(pageSize)

        if not self.m_clipRect.isEmpty():
            p.translate(-self.m_clipRect.left(), -self.m_clipRect.top())
            self.m_page.mainFrame().render(p, QRegion(self.m_clipRect))
        else:
            self.m_page.mainFrame().render(p)

        p.end()
        self.m_page.setViewportSize(viewportSize)
        return image.save(fileName)
Пример #48
0
    def paintEvent(self,event):        
        realSize=min(self.width(),self.height())
       
        painter=QPainter()
        painter.begin(self)
        pen=QPen(Qt.black)
        pen.setWidth(1)
        painter.setPen(Qt.black)
        
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width()/2,self.height()/2)
        painter.scale(float(realSize)/self.scaledSize, float(realSize)/self.scaledSize)
        gradient = QRadialGradient (QPointF(-500,-500), 1500, QPointF(-500,-500));
        gradient.setColorAt(0, QColor(224,224,224));
        gradient.setColorAt(1, QColor(28,28,28));
        painter.setPen(pen);
        painter.setBrush(QBrush(gradient));
        painter.drawEllipse(QPointF(0,0), 500, 500);

        gradient = QRadialGradient (QPointF(500,500), 1500, QPointF(500,500));
        gradient.setColorAt(0, QColor(224,224,224));
        gradient.setColorAt(1, QColor(28,28,28));
        painter.setPen(pen);
        painter.setBrush(QBrush(gradient));
        painter.drawEllipse(QPointF(0,0), 450, 450);
    
        painter.setPen(pen);
        if(self.isChecked()):
            gradient = QRadialGradient (QPointF(-500,-500), 1500, QPointF(-500,-500));
            gradient.setColorAt(0, self._onColor1);
            gradient.setColorAt(1, self._onColor2);
        else:
            gradient = QRadialGradient (QPointF(500,500), 1500, QPointF(500,500));
            gradient.setColorAt(0, self._offColor1);
            gradient.setColorAt(1, self._offColor2);
            
        painter.setBrush(gradient);
        painter.drawEllipse(QPointF(0,0), 400, 400);
        painter.end()
Пример #49
0
	def paintEvent( self, event ):
		# Wenn das Widget disabled ist, muß ich den Alphakanal meiner Farben verändern.
		frameWidth = 16
		dotCenter = QPoint( 0, 0 )
		color = self.__colorEmpty
		if self.__value:
			color = self.__colorFull
		
		# Damit der Rahmen nicht irgendwie abgeschnitten wird, muß der Kreis entsprechend kleiner sein.
		dotRadius = 100
		framePen = QPen( frameWidth )
		framePen.setColor( self.__colorFrame )

		dotDiameter = 2 * dotRadius + frameWidth

		painter = QPainter( self )

		windowWidth = self.width()
		windowHeight = float( self.height() )
		side = min( windowWidth, windowHeight )

		painter.setRenderHint( QPainter.Antialiasing )

		if ( not self.isEnabled() ):
			painter.setOpacity( .5 )

		painter.translate( side / 2, self.height() / 2 )

		painter.scale( side / dotDiameter, side / dotDiameter )

		painter.setPen( framePen )
		painter.setBrush( color )

		painter.save()

		painter.drawEllipse( dotCenter, dotRadius, dotRadius )

		painter.restore()
Пример #50
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(0, 0, self.width(), self.height(), Qt.black)

        painter.setPen(self.coords_pen)
        painter.drawLine(0, self.height () // 2, self.width(), self.height() // 2)
        painter.drawLine(self.width() // 2, 0, self.width() // 2, self.height())

        painter.translate(self.width() // 2, self.height() // 2)
        if (self.image):
            painter.drawImage(self.sp, self.image)

            painter.setPen(self.hbp_pen)
            painter.setBrush(self.hbp_brush)
            painter.drawRect(self.hbp)

            painter.setPen(self.hba_pen)
            painter.setBrush(self.hba_brush)
            painter.drawRect(self.hba)

        painter.setPen(Qt.white)
        painter.drawText(QPoint(0, 20), self.points_file)
        painter.drawText(QPoint(0, 50), self.image_file)
Пример #51
0
    def paintEvent(self, event):
        if self._isRunning:
            anglestep = 360. / self._steps
            fillsteps = self._fillsteps
            factor = min(self.width(), self.height()) / 16.
            bw = self._bw

            p = QPainter(self)
            p.setRenderHint(QPainter.Antialiasing, True)
            p.scale(factor, factor)
            p.setPen(Qt.NoPen)

            for i in range(self._steps):
                x1, y1 = self._coords[i]
                c = fillsteps[self._steps - 1 - i]
                a = anglestep * i
                p.setBrush(QBrush(QColor.fromRgbF(bw, bw, bw, c)))
                p.save()
                p.translate(x1 - 2, y1 - 1)
                p.translate(2, 1)
                p.rotate(a)
                p.translate(-2, -1)
                p.drawPath(self._path)
                p.restore()
Пример #52
0
    def drawArrow(element, painter, option):
        """
        :type element: QStyle.PrimitiveElement
        :type painter: QPainter
        :type option: QStyleOption
        """
        # From windows style but modified to enable AA
        if option.rect.width() <= 1 or option.rect.height() <= 1:
            return

        r = option.rect
        size = min(r.height(), r.width())
        pixmap = QPixmap()
        pixmapName = "arrow-{}-{}-{}-{}-{}".format("$qt_ia",
                                                   int(option.state), element,
                                                   size, option.palette.cacheKey())
        if not QPixmapCache.find(pixmapName, pixmap):
            border = int(size / 5)
            sqsize = int(2 * (size / 2))
            image = QImage(sqsize, sqsize, QImage.Format_ARGB32)
            image.fill(Qt.transparent)
            imagePainter = QPainter(image)
            imagePainter.setRenderHint(QPainter.Antialiasing, True)
            imagePainter.translate(0.5, 0.5)
            a = QPolygon()
            if element == QStyle.PE_IndicatorArrowUp:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize - border, sqsize / 2)
            elif element == QStyle.PE_IndicatorArrowDown:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, sqsize - border, sqsize - border, sqsize / 2)
            elif element == QStyle.PE_IndicatorArrowRight:
                a.setPoints(3, sqsize - border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border)
            elif element == QStyle.PE_IndicatorArrowLeft:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border)

            bsx = 0
            bsy = 0

            if option.state & QStyle.State_Sunken:
                bsx = QApplication.style().pixelMetric(QStyle.PM_ButtonShiftHorizontal)
                bsy = QApplication.style().pixelMetric(QStyle.PM_ButtonShiftVertical)

            bounds = a.boundingRect()
            sx = int(sqsize / 2 - bounds.center().x() - 1)
            sy = int(sqsize / 2 - bounds.center().y() - 1)
            imagePainter.translate(sx + bsx, sy + bsy)

            if not (option.state & QStyle.State_Enabled):
                foreGround = QColor(150, 150, 150, 150)
                imagePainter.setBrush(option.palette.mid().color())
                imagePainter.setPen(option.palette.mid().color())
            else:
                shadow = QColor(0, 0, 0, 100)
                imagePainter.translate(0, 1)
                imagePainter.setPen(shadow)
                imagePainter.setBrush(shadow)
                foreGround = QColor(255, 255, 255, 210)
                imagePainter.drawPolygon(a)
                imagePainter.translate(0, -1)
                imagePainter.setPen(foreGround)
                imagePainter.setBrush(foreGround)
            imagePainter.drawPolygon(a)
            imagePainter.end()
            pixmap = QPixmap.fromImage(image)
            QPixmapCache.insert(pixmapName, pixmap)

        xOffset = int(r.x() + (r.width() - size) / 2)
        yOffset = int(r.y() + (r.height() - size) / 2)
        painter.drawPixmap(xOffset, yOffset, pixmap)
Пример #53
0
    def paintInfoColumn(self, painter, option, index, width_limit = 0):
        left = option.rect.left() + 3
        top = option.rect.top()
        width = option.rect.width() - width_limit

        pixmap = QPixmap(option.rect.size())
        pixmap.fill(Qt.transparent)

        p = QPainter(pixmap)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.translate(-option.rect.topLeft())

        textInner = 2 * ICON_PADDING + ROW_HEIGHT - 10
        itemHeight = ROW_HEIGHT + 2 * ICON_PADDING

        margin = left + ICON_PADDING - 10

        title = index.model().data(index, NameRole).toString()
        summary = index.model().data(index, SummaryRole).toString()
        ptype = str(index.model().data(index, TypeRole).toString())
        rate = int(index.model().data(index, RateRole).toInt()[0])
        installed = index.model().data(index, InstalledRole).toBool()

        # We need to request update if its not possible to get meta data about the package
        try:
            # Get Package Icon if exists
            _icon = index.model().data(index, Qt.DecorationRole).toString()
        except:
            p.end()
            painter.drawPixmap(option.rect.topLeft(), pixmap)
            self.parent.requestUpdate()
            return

        icon = None

        if _icon:
            overlay = [CHECK_ICON] if installed else []
            KIconLoader._forceCache = True
            pix = KIconLoader.loadOverlayed(_icon, overlay, 32)
            if not pix.isNull():
                icon = QIcon(pix.scaled(QSize(32, 32), Qt.KeepAspectRatio, Qt.SmoothTransformation))
            KIconLoader._forceCache = False

        if not icon:
            icon = self.defaultIcon if not installed else self.defaultInstalledIcon

        # Paint the Icon
        icon.paint(p, margin, top + ICON_PADDING, ROW_HEIGHT, ROW_HEIGHT, Qt.AlignCenter)

        fix_pos = 0
        if index.model().columnCount() <= 1:
            fix_pos = 22

        if config.USE_APPINFO:
            # Rating Stars
            for _rt_i in range(5):
                self._rt_0.paint(p, width + 10 * _rt_i - 30 - fix_pos, top + ROW_HEIGHT / 4, 10, 10, Qt.AlignCenter)
            for _rt_i in range(rate):
                self._rt_1.paint(p, width + 10 * _rt_i - 30 - fix_pos, top + ROW_HEIGHT / 4, 10, 10, Qt.AlignCenter)

        foregroundColor = option.palette.color(QPalette.Text)
        p.setPen(foregroundColor)

        # Package Name
        p.setFont(self.boldFont)
        p.drawText(left + textInner, top, width - textInner, itemHeight / 2, Qt.AlignBottom | Qt.AlignLeft, title)

        tagWidth = 0

        _component_width = 0
        if self.parent.showComponents:
            component = str(index.model().data(index, ComponentRole).toString())
            widthOfTitle = self.boldFontFM.width(title) + 6 + left + textInner

            p.setFont(self.tagFont)
            rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap, component)
            p.setPen(LIGHTGREEN)
            p.setBrush(LIGHTGREEN)
            p.drawRoundRect(widthOfTitle , top + 12, rect.width() + 4, rect.height(), 10, 10)
            p.setPen(DARKGREEN)
            p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(), Qt.AlignCenter, component)
            p.setPen(foregroundColor)
            _component_width = rect.width() + 8

        if self.parent.showIsA:
            isa = str(index.model().data(index, IsaRole).toString())
            if not isa == '':
                widthOfTitle = self.boldFontFM.width(title) + 6 + left + textInner + _component_width

                p.setFont(self.tagFont)
                rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap, isa)
                p.setPen(LIGHTBLUE)
                p.setBrush(LIGHTBLUE)
                p.drawRoundRect(widthOfTitle , top + 12, rect.width() + 4, rect.height(), 10, 10)
                p.setPen(DARKVIOLET)
                p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(), Qt.AlignCenter, isa)
                p.setPen(foregroundColor)
                _component_width += rect.width() + 8

        if ptype not in ('None', 'normal'):
            widthOfTitle = self.boldFontFM.width(title) + 6 + left + textInner + _component_width
            p.setFont(self.tagFont)
            rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap, self.types[ptype][1])
            p.setPen(self.types[ptype][0])
            p.setBrush(self.types[ptype][0])
            p.drawRoundRect(widthOfTitle, top + 12, rect.width() + 4, rect.height(), 10, 10)
            p.setPen(WHITE)
            p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(), Qt.AlignCenter, self.types[ptype][1])
            p.setPen(foregroundColor)
            tagWidth = rect.width()

        # Package Summary
        p.setFont(self.normalFont)
        foregroundColor.setAlpha(160)
        p.setPen(foregroundColor)
        elided_summary = self.normalFontFM.elidedText(summary, Qt.ElideRight, width - textInner - tagWidth - 22)
        p.drawText(left + textInner, top + itemHeight / 2, width - textInner, itemHeight / 2, Qt.TextDontClip, elided_summary)
        foregroundColor.setAlpha(255)
        p.setPen(foregroundColor)

        buttonStyle = None
        if self.rowAnimator.currentRow() == index.row():
            description = index.model().data(index, DescriptionRole).toString()
            size = index.model().data(index, SizeRole).toString()
            homepage = index.model().data(index, HomepageRole).toString()
            installedVersion = str(index.model().data(index, InstalledVersionRole).toString())
            version = index.model().data(index, VersionRole)

            # Package Detail Label
            position = top + ROW_HEIGHT

            p.setFont(self.normalDetailFont)
            baseRect = QRect(left, position, width - 8, option.rect.height())
            rect = self.normalDetailFontFM.boundingRect(baseRect, Qt.TextWordWrap | Qt.TextDontClip, description)
            p.drawText(left + 2, position, width - 8, rect.height(), Qt.TextWordWrap | Qt.TextDontClip, description)

            # Package Detail Homepage
            position += rect.height() + 4

            p.setFont(self.boldDetailFont)
            p.drawText(left + ICON_SIZE , position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['website'])

            p.setFont(self.normalDetailFont)
            homepage = self.normalDetailFontFM.elidedText(homepage, Qt.ElideRight, width - self._titleFM['website'])
            rect = self.normalDetailFontFM.boundingRect(option.rect, Qt.TextSingleLine, homepage)
            self.rowAnimator.hoverLinkFilter.link_rect = QRect(left + self._titleFM['website'] + 2, position + 2 + 32, rect.width(), rect.height())

            p.setPen(option.palette.color(QPalette.Link))
            p.drawText(left + self._titleFM['website'], position, width, rect.height(), Qt.TextSingleLine, homepage)
            p.setPen(foregroundColor)

            # Package Detail Version
            position += rect.height()

            p.setFont(self.boldDetailFont)
            p.drawText(left + ICON_SIZE , position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['release'])

            p.setFont(self.normalDetailFont)
            rect = self.normalDetailFontFM.boundingRect(option.rect, Qt.TextWordWrap, version.toString())
            p.drawText(left + self._titleFM['release'], position, width, rect.height(), Qt.TextWordWrap, version.toString())

            if not installedVersion == '':
                position += rect.height()

                p.setFont(self.boldDetailFont)
                p.drawText(left + ICON_SIZE , position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['installVers'])

                p.setFont(self.normalDetailFont)
                rect = self.normalDetailFontFM.boundingRect(option.rect, Qt.TextWordWrap, installedVersion)
                p.drawText(left + self._titleFM['installVers'], position, width, rect.height(), Qt.TextWordWrap, installedVersion)

            # Package Detail Repository
            repository = index.model().data(index, RepositoryRole).toString()
            if not repository == '':
                repository = i18n('Unknown')  if repository == 'N/A' else repository
                position += rect.height()

                p.setFont(self.boldDetailFont)
                p.drawText(left + ICON_SIZE , position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['repository'])

                p.setFont(self.normalDetailFont)
                p.drawText(left + self._titleFM['repository'], position, width, itemHeight / 2, Qt.TextWordWrap, repository)

            # Package Detail Size
            position += rect.height()

            p.setFont(self.boldDetailFont)
            p.drawText(left + ICON_SIZE , position, width - textInner, itemHeight / 2, Qt.AlignLeft, self._titles['size'])

            p.setFont(self.normalDetailFont)
            p.drawText(left + self._titleFM['size'], position, width, itemHeight / 2, Qt.TextWordWrap, size)
            position += rect.height()
            self.rowAnimator.max_height = position - top + 8

            # Package More info button
            opt = QStyleOptionViewItemV4(option)

            buttonStyle = QStyleOptionButton()
            if option.state & QStyle.State_MouseOver or option.state & QStyle.State_HasFocus:
                buttonStyle.state |= QStyle.State_HasFocus
            buttonStyle.state |= QStyle.State_Enabled
            buttonStyle.text = i18n("Details")

            buttonStyle.rect = QRect(width - 100, position - 22, 100, 22)

        p.end()

        # FIXME
        # if option.state & QStyle.State_HasFocus and self.animatable:
        #     option.state |= QStyle.State_MouseOver
            # Use Plastique style to draw focus rect like MouseOver effect of Oxygen.
            # self.plastik.drawPrimitive(QStyle.PE_FrameLineEdit, option, painter, None)

        if not self.rowAnimator.running() and buttonStyle:
            if self.show_details_button and (installed or config.USE_APPINFO):
                PackageDelegate.AppStyle().drawControl(QStyle.CE_PushButton, buttonStyle, painter, None)
                self.rowAnimator.hoverLinkFilter.button_rect = QRect(buttonStyle.rect)

        painter.drawPixmap(option.rect.topLeft(), pixmap)
        del pixmap
Пример #54
0
 def drawImage(self, imageid):
     cache = image_cache.cache
     cellColoring = self.cellColoring
     wallColoring = self.wallColoring
     pointColoring = self.pointColoring
     ellipsisDraw = self.ellipsisDraw
     overSampling = self.overSampling
     extraDrawing = self.extraDrawing
     bgColor = self.bgColor.rgb()
     result = self.result
     if self.result_type == "Data":
         data = result
         img_name = result.images_name[imageid]
     else:
         data = result.data
         img_name = result.images[imageid]
     #scale = data.images_scale[img_name]
     min_scale = data.minScale()
     img = cache.image(data.image_path(img_name))
     img_data = data[img_name]
     size = self._crop.size()
     pix = QImage(size*overSampling, QImage.Format_ARGB32)
     pix.fill(bgColor)
     painter = QPainter()
     if not painter.begin(pix):
         self.abort("Cannot create painter on QImage")
         return None, None, None
     painter.setRenderHints(QPainter.SmoothPixmapTransform, True)
     painter.setRenderHints(QPainter.Antialiasing, True)
     if overSampling > 1:
         painter.scale(overSampling, overSampling)
     painter.translate(-self._crop.topLeft())
     painter.save()
     painter.translate(self.translate)
     log_debug("Translating: %gx%g" % (self.translate.x(), self.translate.y()) )
     painter.scale(1/min_scale, 1/min_scale)
     painter.save()
     matrix = img_data.matrix()
     painter.setWorldTransform(matrix, True)
     painter.drawImage(QPoint(0,0), img)
     painter.restore()
     #pt_matrix = QTransform()
     #pt_matrix.scale(1/min_scale, 1/min_scale)
     #painter.setTransform(pt_matrix, True)
     cellColoring.startImage(painter, imageid)
     wallColoring.startImage(painter, imageid)
     for ed in extraDrawing:
         ed.startImage(painter, imageid)
     if self.result_type == "Growth":
         cells = result.cells[imageid]
         walls = result.walls[imageid]
     else:
         cells = img_data.cells
         walls = set()
         for cid in img_data.cells:
             pts = [ pt for pt in data.cells[cid] if pt in img_data ]
             if len(pts) > 1:
                 for i in range(len(pts)):
                     walls.add(data.wallId(pts[i-1], pts[i]))
     # Now, draw the cells and the ellipsis
     for cid in cells:
         painter.setPen(Qt.NoPen)
         color = cellColoring(imageid, cid)
         painter.setBrush(color)
         pts = data.cellAtTime(cid, img_data.index)
         if pts:
             pts.append(pts[0])
             ppts = []
             for p1,p2 in zip(pts[:-1], pts[1:]):
                 ppts.append(img_data[p1])
                 ppts.extend(img_data.walls[p1,p2])
             ppts.append(ppts[0])
             poly = QPolygonF(ppts)
             painter.drawPolygon(poly)
     # And draw the walls
     wallThickness = self.wallThickness*min_scale
     for wid in walls:
         color = wallColoring(imageid, wid)
         if color.alpha() > 0:
             pen = QPen(color)
             pen.setWidthF(wallThickness)
             painter.setPen(pen)
             pts = [img_data[wid[0]]] + img_data.walls[wid[0], wid[1]] + [img_data[wid[1]]]
             #painter.drawLine(img_data[wid[0]], img_data[wid[1]])
             painter.drawPolyline(*pts)
     # Then, draw the points
     pointSize = self.pointSize*min_scale
     pointLineColor = self.pointLineColor
     pointLineThickness = self.pointLineThickness*min_scale
     log_debug("pointSize = %g" % pointSize)
     for pid in img_data:
         color = pointColoring(imageid, pid)
         if color.alpha() > 0:
             pen = QPen(pointLineColor)
             pen.setWidthF(pointLineThickness)
             brush = QBrush(color)
             painter.setPen(pen)
             painter.setBrush(brush)
             pos = img_data[pid]
             rect = QRectF(pos.x()-pointSize, pos.y()-pointSize, 2*pointSize, 2*pointSize)
             painter.drawEllipse(rect)
     if ellipsisDraw.plot:
         for cid in cells:
             pts = data.cellAtTime(cid, img_data.index)
             if pts:
                 pts.append(pts[0])
                 ppts = []
                 for p1,p2 in zip(pts[:-1], pts[1:]):
                     ppts.append(img_data[p1])
                     ppts.extend(img_data.walls[p1,p2])
                 ppts.append(ppts[0])
                 #poly = QPolygonF(ppts)
                 #painter.drawPolygon(poly)
                 ellipsisDraw(painter, imageid, cid, ppts, min_scale)
     # At last, draw the extra data
     for ed in extraDrawing:
         ed(painter, imageid)
     tr = painter.worldTransform()
     painter.restore()
     pic_w = wallColoring.finalizeImage(painter, imageid, tr, self.crop)
     pic_c = cellColoring.finalizeImage(painter, imageid, tr, self.crop)
     for ed in extraDrawing:
         ed.finalizeImage(painter, imageid, tr, self.crop)
     painter.end()
     return pix, pic_w, pic_c
Пример #55
0
	def paintEvent( self, event ):
		# Wenn das Widget disabled ist, muß ich den Alphakanal meiner Farben verändern.
		frameWidth = 16
		dotCenter = QPoint( 0, 0 )
		shiftCenter = dotCenter
		
		# Damit der Rahmen nicht irgendwie abgeschnitten wird, muß der Kreis entsprechend kleiner sein.
		dotRadius = 100
		framePen = QPen()
		framePen.setWidth(frameWidth )
		framePen.setColor( self._colorFrame )

		dotDiameter = 2 * dotRadius + frameWidth

		painter = QPainter( self )

		windowWidth = self.width() // self.maximum
		windowHeight = float( self.height() )
		side = min( windowWidth, windowHeight )

		painter.setRenderHint( QPainter.Antialiasing )

		if ( not self.isEnabled() ):
			painter.setOpacity( .5 )

		painter.translate( side / 2, self.height() / 2 )

		painter.scale( side / dotDiameter, side / dotDiameter )

		painter.setPen( framePen )
		painter.setBrush( self._colorFull )

		painter.save()

		for i in range(self.value):
			shiftCenter = dotCenter + QPoint( 0 + dotDiameter * i, 0 )
			painter.drawEllipse( shiftCenter, dotRadius, dotRadius )
	## 		if (v_forbiddenValues.contains(i+1)){
	## 			painter.drawEllipse(shiftCenter, dotRadius/2, dotRadius/2);

		painter.restore()

		painter.setBrush( QColor(Config.COLOR_BONUS) )

		painter.save()

		for i in range(self.value, self.value + self.__bonusValue):
			shiftCenter = dotCenter + QPoint( 0 + dotDiameter * i, 0 )
			painter.drawEllipse( shiftCenter, dotRadius, dotRadius )

		painter.restore()

		painter.setBrush( self._colorEmpty )

		painter.save()

		for i in range(self.value + self.__bonusValue, self.maximum):
			shiftCenter = dotCenter + QPoint( 0 + dotDiameter * i, 0 )
			painter.drawEllipse( shiftCenter, dotRadius, dotRadius )

			j = i+1
			if ( j in self.forbiddenValues ):
				dotRadiusHalf = dotRadius / 2
				painter.drawLine( shiftCenter.x() - dotRadiusHalf, shiftCenter.y() - dotRadiusHalf, shiftCenter.x() + dotRadiusHalf, shiftCenter.y() + dotRadiusHalf )
				painter.drawLine( shiftCenter.x() - dotRadiusHalf, shiftCenter.y() + dotRadiusHalf, shiftCenter.x() + dotRadiusHalf, shiftCenter.y() - dotRadiusHalf )

		painter.restore()
Пример #56
0
class QtRenderer(Renderer):
    """An implementation of :class:`~renderer.Renderer` for PyQt4.
       
       This renderer will draw on any `QPaintDevice`
    """
    def __init__(self, paint_device):
        """Creates a new renderer based on a QPaintDevice pd"""
        self._grid_pen = QPen(QColor(0x808080))
        self._grid_pen.setStyle(Qt.DashLine)
        self._painter = None
        Renderer.__init__(self, paint_device)

    def set_canvas(self, canvas):
        """Tell the renderer to draw on canvas
        The type of canvas is implementation-dependent"""
        if self._painter is not None:
            self._painter.restore()
            self._painter.restore()
            self._painter.end()
        
        self._paintdevice = canvas
        self._painter = QPainter(canvas)
        self._painter.setRenderHint(QPainter.Antialiasing)

        # invert the y axis
        self._painter.scale(1,-1)
        self._painter.translate(0,-canvas.height())

        Renderer.set_canvas(self,canvas)

    def _get_canvas_size(self,pd):
        """Get the canvas size tuple (width,height)"""
        return (pd.width(), pd.height())

    def push_state(self):
        """Store the current state on the stack.
        Current state includes default pose, pen and brush"""
        ### FIXME store things
        self._painter.save()

    def pop_state(self):
        """Restore the last saved state from the stack
        The state includes default pose, pen and brush"""
        ### FIXME store things
        self._painter.restore()

    def _calculate_bounds(self):
        transform = self._painter.worldTransform().inverted()[0]
        xs,ys = zip(
                    transform.map(0.0,0.0),
                    transform.map(0.0,float(self.size[1])),
                    transform.map(float(self.size[0]),float(self.size[1])),
                    transform.map(float(self.size[0]),0.0)
                    )

        self._bounds = (min(xs), min(ys), max(xs), max(ys))

    def _draw_grid(self):
        self.reset_pose()
        self._painter.setPen(self._grid_pen)
        xmin, ymin, xmax, ymax = self._bounds

        # Determine min/max x & y line indices:
        x_ticks = (int(xmin//self._grid_spacing), int(xmax//self._grid_spacing + 1))
        y_ticks = (int(ymin//self._grid_spacing), int(ymax//self._grid_spacing + 1))

        self._painter.drawLines(
            [QLineF(xmin, i * self._grid_spacing,
                    xmax, i * self._grid_spacing)
                for i in range(*y_ticks)])
        self._painter.drawLines(
            [QLineF(i * self._grid_spacing, ymin,
                    i * self._grid_spacing, ymax)
                for i in range(*x_ticks)])

    def scale(self, factor):
        """Scale drawing operations by factor
        To be implemented in subclasses."""
        self._painter.scale(factor,factor)

    def rotate(self, angle):
        """Rotate canvas by angle (in radians)
        To be implemented in subclasses."""
        self._painter.rotate(degrees(angle))

    def translate(self, dx, dy):
        """Translate canvas by dx, dy
        To be implemented in subclasses."""
        self._painter.translate(dx,dy)

    def clear_screen(self):
        """Erases the current screen with a white brush"""
        self._painter.save()
        self._painter.resetTransform()
        self.set_pen(0xFFFFFF)
        self.set_brush(0xFFFFFF)
        self.draw_rectangle(0,0,self.size[0],self.size[1])
        self._painter.restore()
        Renderer.clear_screen(self)

    @staticmethod
    def __qcolor(color):
        """Returns qcolor for a given ARGB color"""
        c = QColor(color)
        if color > 0xFFFFFF:
            c.setAlpha((color >> 24) & 0xFF)
        return c

    def set_pen(self,color=0, thickness=0):
        """Sets the line color and thickness.
        Color is interpreted as 0xAARRGGBB."""
        if color is None:
            self._painter.setPen(Qt.NoPen)
        else:
            self._painter.setPen(QPen(self.__qcolor(color),thickness))

    def set_brush(self,color):
        """Sets the fill color.
        Color is interpreted as 0xAARRGGBB."""
        if color is None:
            self._painter.setBrush(Qt.NoBrush)
        else:
            self._painter.setBrush(self.__qcolor(color))

    def draw_polygon(self,points):
        """Draws a polygon.
        Expects a list of points as a list of tuples or as a numpy array."""
        self._painter.drawPolygon(QPolygonF([QPointF(*point[:2]) for point in points]))

    def draw_ellipse(self, cx, cy, ra, rb = None):
        """Draws an ellipse."""
        if rb is None:
            rb = ra
        self._painter.drawEllipse(QRectF(cx-ra,cy-ra,2*ra,2*rb))

    def draw_rectangle(self, x, y, w, h):
        """Draws a rectangle."""
        self._painter.drawRect(QRectF(x,y,w,h))

    def draw_text(self, text, x, y, bgcolor = 0):
        """Draws a text string at the defined position."""
        pass

    def draw_line(self, x1, y1, x2, y2):
        """Draws a line using the current pen from (x1,y1) to (x2,y2)"""
        self._painter.drawLine(QLineF(x1,y1,x2,y2))
Пример #57
0
    def paintEvent(self, event):
        painter = QPainter(self)
        width = self.width()
        height = self.height()

        if self.scales_visible:
            curve_width = width - self.y_scale.total_width - self.curve_to_scale - self.curve_outer_border
            curve_height = height - self.y_scale_height_offset - self.x_scale.total_height - self.curve_to_scale
        else:
            curve_width = width - self.curve_outer_border - self.curve_outer_border
            curve_height = height - self.curve_outer_border - self.curve_outer_border

        if DEBUG:
            painter.fillRect(0, 0, width, height, Qt.green)

        # fill canvas
        if self.scales_visible:
            canvas_x = self.y_scale.total_width + self.curve_to_scale - self.curve_outer_border
            canvas_y = self.y_scale_height_offset - self.curve_outer_border
        else:
            canvas_x = 0
            canvas_y = 0

        canvas_width = self.curve_outer_border + curve_width + self.curve_outer_border
        canvas_height = self.curve_outer_border + curve_height + self.curve_outer_border

        painter.fillRect(canvas_x, canvas_y, canvas_width, canvas_height, self.canvas_color)

        # draw cross hair at cursor position
        if self.cross_hair_visible:
            p = self.mapFromGlobal(QCursor.pos())
            p_x = p.x()
            p_y = p.y()

            if p_x >= canvas_x and p_x < canvas_x + canvas_width and \
               p_y >= canvas_y and p_y < canvas_y + canvas_height:
                painter.setPen(QPen(QColor(190, 190, 190), 1, Qt.DashLine))
                painter.drawLine(canvas_x, p_y, canvas_x + canvas_width - 1, p_y)
                painter.drawLine(p_x, canvas_y, p_x, canvas_y + canvas_height - 1)

        # draw canvas border
        if self.curve_outer_border > 0:
            painter.setPen(QColor(190, 190, 190))
            painter.drawRect(canvas_x, canvas_y, canvas_width - 1, canvas_height - 1) # -1 to accommodate the 1px width of the border
            painter.setPen(Qt.black)

        if DEBUG:
            painter.fillRect(canvas_x + self.curve_outer_border,
                             canvas_y + self.curve_outer_border,
                             curve_width,
                             curve_height,
                             Qt.cyan)

        # draw scales
        y_min_scale = self.y_scale.value_min
        y_max_scale = self.y_scale.value_max

        factor_x = float(curve_width) / self.history_length_x
        factor_y = float(curve_height - 1) / max(y_max_scale - y_min_scale, EPSILON) # -1 to accommodate the 1px width of the curve

        if self.scales_visible:
            self.draw_x_scale(painter, factor_x)
            self.draw_y_scale(painter, curve_height, factor_y)

        # draw curves
        if self.x_min != None and self.x_max != None:
            x_min = self.x_min
            x_max = self.x_max

            if self.scales_visible:
                curve_x_offset = 0
            else:
                curve_x_offset = round((self.history_length_x - (x_max - x_min)) * factor_x)

            painter.save()
            painter.translate(canvas_x + self.curve_outer_border + curve_x_offset,
                              canvas_y + self.curve_outer_border + curve_height - 1 + self.curve_y_offset) # -1 to accommodate the 1px width of the curve
            painter.scale(factor_x, -factor_y)
            painter.translate(-x_min, -y_min_scale)

            for c in range(len(self.curves_x)):
                if not self.curves_visible[c]:
                    continue

                curve_x = self.curves_x[c]
                curve_y = self.curves_y[c]
                path = QPainterPath()
                lineTo = path.lineTo

                path.moveTo(curve_x[0], curve_y[0])

                for i in xrange(1, len(curve_x)):
                    lineTo(curve_x[i], curve_y[i])

                painter.setPen(self.plots[c][1])
                painter.drawPath(path)

            painter.restore()
Пример #58
0
    def paintEvent(self, event):
        """Adapted from http://doc.qt.io/qt-5/qtwidgets-widgets-analogclock-example.html"""
        HOURHAND = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -55)])
        MINUTEHAND = QPolygon([QPoint(7, 8), QPoint(-7, 8), QPoint(0, -87)])
        HOURCOLOR = QColor(Qt.black)
        MINUTECOLOR = QColor(0x11, 0x11, 0x11, 0xAA)

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

        # Background (night/day)
        if self._time_to is not None:
            time = self._time_to.time()
            hour_offset = time.hour() + time.minute() / 60
            DAY, NIGHT = QColor(Qt.white), QColor('#5555ff')
            if 7 <= hour_offset <= 19:
                background = DAY
            elif 6 <= hour_offset <= 7:
                palette = GradientPaletteGenerator(NIGHT, DAY)
                background = palette[(hour_offset - 6) / (7 - 6)]
            elif 19 <= hour_offset <= 20:
                palette = GradientPaletteGenerator(DAY, NIGHT)
                background = palette[(hour_offset - 19) / (20 - 19)]
            else:
                assert hour_offset < 7 or hour_offset > 20
                background = NIGHT
            painter.setBrush(QBrush(background))
            painter.setPen(HOURCOLOR)
            painter.drawEllipse(-SIDE / 2, -SIDE / 2, SIDE, SIDE)

        # Minute tickmarks
        painter.save()
        painter.setPen(MINUTECOLOR)
        for j in range(60):
            painter.drawLine(94, 0, 97, 0)
            painter.rotate(6)
        painter.restore()

        # Hour tickmarks
        painter.save()
        painter.setPen(HOURCOLOR)
        for _ in range(12):
            painter.drawLine(88, 0, 98, 0)
            painter.rotate(30)
        painter.restore()

        # Hour span
        if self._time_from is not None:
            time_from = self._time_from.time()
            time_to = self._time_to.time()
            if time_from.secsTo(time_to) / 3600 > .2:  # Don't draw really small intervals
                hour_from = (time_from.hour() + time_from.minute() / 60) % 12 - 3
                hour_to = (time_to.hour() + time_to.minute() / 60) % 12 - 3
                startAngle = -hour_to * 30 * 16
                spanAngle = -hour_from * 30 * 16 - startAngle
                color = QColor(0xFF, 0xFF, 0, 0xAA)
                painter.save()
                painter.setBrush(QBrush(color, Qt.DiagCrossPattern))
                painter.setPen(color.darker(180))
                painter.drawPie(-SIDE / 2, -SIDE / 2, SIDE, SIDE, startAngle, spanAngle)
                painter.restore()

        # Hour and minute hand
        if self._time_to is not None:
            time = self._time_to.time()

            painter.setPen(Qt.NoPen)

            painter.save()
            painter.setBrush(HOURCOLOR)
            painter.rotate(30 * (time.hour() + time.minute() / 60))
            painter.drawConvexPolygon(HOURHAND)
            painter.restore()

            painter.save()
            painter.setBrush(MINUTECOLOR)
            painter.rotate(6 * (time.minute() + time.second() / 60))
            painter.drawConvexPolygon(MINUTEHAND)
            painter.restore()