Example #1
0
    def render(self, fileName, width, height):
        self.setViewportSize(QSize(width, height))

        fileInfo = QFileInfo(fileName)
        dir = QDir()
        dir.mkpath(fileInfo.absolutePath())
        viewportSize = self.viewportSize()
        pageSize = self.mainFrame().contentsSize()
        if pageSize.isEmpty():
            return False

        buffer = QImage(pageSize, QImage.Format_ARGB32)
        buffer.fill(qRgba(255, 255, 255, 0))
        p =  QPainter(buffer)

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

        self.setViewportSize(pageSize)
        self.mainFrame().render(p)
        p.end()

        self.setViewportSize(viewportSize)

        return buffer.save(fileName)
Example #2
0
    def __init__(self, parent, scene, view):
        super(QNodesEditor, self).__init__(parent)

        self.scene = scene
        self.scene.installEventFilter(self)

        gridSize = 25
        gridMap = QPixmap(gridSize,gridSize)
        gridPainter = QPainter(gridMap)
        gridPainter.fillRect(0,0,gridSize,gridSize, QApplication.palette().window().color().darker(103))
        gridPainter.fillRect(1,1,gridSize-2,gridSize-2, QApplication.palette().window())
        gridPainter.end()
        self.scene.setBackgroundBrush( QBrush(gridMap) )

        originSize = 50
        originItem = QGraphicsPathItem()
        path = QPainterPath()
        path.moveTo(0,-originSize)
        path.lineTo(0,originSize)
        path.moveTo(-originSize,0)
        path.lineTo(originSize,0)
        originItem.setPath(path)
        originItem.setPen(QPen(QApplication.palette().window().color().darker(110),2))
        originItem.setZValue(-2)
        self.scene.addItem(originItem)

        self.view = view
        self.view.setDragMode(QGraphicsView.RubberBandDrag)
        self.view.setRenderHint(QPainter.Antialiasing)

        self.connection = None
Example #3
0
 def paintEvent(self, event):
     contents_y = self.edit.verticalScrollBar().value()
     page_bottom = contents_y + self.edit.viewport().height()
     font_metrics = self.fontMetrics()
     current_block = self.edit.document().findBlock(self.edit.textCursor().position())
     painter = QPainter(self)
     line_count = 0
     block = self.edit.document().begin()
     while block.isValid():
         line_count += 1
         position = self.edit.document().documentLayout().blockBoundingRect(block).topLeft()
         if position.y() > page_bottom:
             break
         bold = False
         if block == current_block:
             bold = True
             font = painter.font()
             font.setBold(True)
             painter.setFont(font)
             self.current = line_count
         painter.drawText(
             self.width() - font_metrics.width(str(line_count)) - 10,
             round(position.y()) - contents_y + font_metrics.ascent(),
             str(line_count),
         )
         if bold:
             font = painter.font()
             font.setBold(False)
             painter.setFont(font)
         block = block.next()
     self.highest_line = line_count
     painter.end()
     QWidget.paintEvent(self, event)
Example #4
0
class View(QMainWindow, Ui_MainWindow):
    points = []

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.show()
        self.painter = QPainter()

    def paintEvent(self, event):
        self.painter.begin(self)

        for p in self.points:
            self.painter.setPen(QColor(p.clr[0], p.clr[1], p.clr[2]))
            self.painter.drawEllipse(p.x.value, p.y.value, p.rad.value,
                                     p.rad.value)

        self.painter.end()

    def resizeEvent(self, event):
        for p in self.points:
            p.resize(self.canvas.size().width(), self.canvas.size().height())

    def closeEvent(self, event):
        for p in self.points:
            p.join()

        event.accept()
Example #5
0
    def set_clipboard_image(self):
        """Export the formatted output to an image and store it in the
        clipboard.

        The image stored in the clipboard is a PNG file with alpha
        transparency.

        """
        div = self.view.page().mainFrame().findFirstElement('.output')
        images = {}
        for background in (Qt.transparent, Qt.white):
            image = QImage(div.geometry().size(),
                           QImage.Format_ARGB32_Premultiplied)
            image.fill(background)
            painter = QPainter(image)
            div.render(painter)
            painter.end()
            images[background] = image

        # Windows needs this buffer hack to get alpha transparency in
        # the copied PNG.
        buffer_ = QBuffer()
        buffer_.open(QIODevice.WriteOnly)
        images[Qt.transparent].save(buffer_, 'PNG')
        buffer_.close()
        data = QMimeData()
        data.setData('PNG', buffer_.data())
        data.setImageData(images[Qt.white])
        QApplication.clipboard().setMimeData(data)
Example #6
0
    def capture(self, region=None, selector=None,
            format=QImage.Format_ARGB32_Premultiplied):
        """Returns snapshot as QImage.

        :param region: An optional tuple containing region as pixel
            coodinates.
        :param selector: A selector targeted the element to crop on.
        :param format: The output image format.
        """
        if region is None and selector is not None:
            region = self.region_for_selector(selector)
        if region:
            x1, y1, x2, y2 = region
            w, h = (x2 - x1), (y2 - y1)
            image = QImage(QSize(x2, y2), format)
            painter = QPainter(image)
            self.main_frame.render(painter)
            painter.end()
            image = image.copy(x1, y1, w, h)
        else:
            self.main_frame.setScrollBarPolicy(QtCore.Qt.Vertical,
                QtCore.Qt.ScrollBarAlwaysOff)
            self.main_frame.setScrollBarPolicy(QtCore.Qt.Horizontal,
                QtCore.Qt.ScrollBarAlwaysOff)
            self.page.setViewportSize(self.main_frame.contentsSize())
            image = QImage(self.page.viewportSize(), format)
            painter = QPainter(image)
            self.main_frame.render(painter)
            painter.end()
        return image
Example #7
0
    def capture(self,
                region=None,
                selector=None,
                format=QImage.Format_ARGB32_Premultiplied):
        """Returns snapshot as QImage.

        :param region: An optional tuple containing region as pixel
            coodinates.
        :param selector: A selector targeted the element to crop on.
        :param format: The output image format.
        """
        if region is None and selector is not None:
            region = self.region_for_selector(selector)
        if region:
            x1, y1, x2, y2 = region
            w, h = (x2 - x1), (y2 - y1)
            image = QImage(QSize(x2, y2), format)
            painter = QPainter(image)
            self.main_frame.render(painter)
            painter.end()
            image = image.copy(x1, y1, w, h)
        else:
            self.main_frame.setScrollBarPolicy(QtCore.Qt.Vertical,
                                               QtCore.Qt.ScrollBarAlwaysOff)
            self.main_frame.setScrollBarPolicy(QtCore.Qt.Horizontal,
                                               QtCore.Qt.ScrollBarAlwaysOff)
            self.page.setViewportSize(self.main_frame.contentsSize())
            image = QImage(self.page.viewportSize(), format)
            painter = QPainter(image)
            self.main_frame.render(painter)
            painter.end()
        return image
    def paint(self, canvas, is_secondary_color=False, additional_flag=False):
        pen = QPen()

        if is_secondary_color:
            pen.setColor(self.data_singleton.secondary_color)
        else:
            pen.setColor(self.data_singleton.primary_color)

        painter = QPainter(canvas.image)
        painter.setRenderHint(QPainter.Antialiasing)
        pen.setWidth(self.data_singleton.pen_size)
        pen.setStyle(Qt.SolidLine)
        pen.setCapStyle(Qt.RoundCap)
        pen.setJoinStyle(Qt.RoundJoin)

        painter.setPen(pen)

        if is_secondary_color:
            painter.setBrush(self.data_singleton.primary_color)
        else:
            painter.setBrush(self.data_singleton.secondary_color)

        if self._start_point != self._end_point:
            painter.drawRect(QRect(self._start_point, self._end_point))

        painter.end()

        canvas.edited = True
        canvas.update()
Example #9
0
    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.save()
        self.rect = painter.viewport()
        self.rect.adjust(0, 0, -1, -1)
        painter.drawRect(QRectF(self.rect))
        
        self.prj.setupPrism(self.rect.height(), 68)
        self.prj.setupProjectionMatrix(self.alef, self.bet)
        
        # draw the prism
        self.drawCubick(painter, [0, 0, 0], 63, 16)
        
        mineCube = self.parent.presenter.mineCube
        for y in range(len(mineCube)):
            for z in range(len(mineCube[0])):
                for x in range(len(mineCube[0][0])):
                    if mineCube[y][z][x] in self.parent.selectedMinerals.list_:
                        colo = self.parent.selectedMinerals.\
                                                     getColor(mineCube[y][z][x])
                        self.drawCubick(painter, [x, y, z], color=colo)

        self.drawSliceCursor(painter, self.parent.presenter.elevation)

        painter.restore()
        painter.end()
        del painter
Example #10
0
    def saveAsBitmap(self, fn):
        """
        Save bar image as a jpg file. Overwrites a file already existing in
        filesystem.

        https://stackoverflow.com/questions/7451183/how-to-create-image-file\
        -from-qgraphicsscene-qgraphicsview#11642517

        Args:
            fn: Filename
        Returns:
            True on success
        """
        size = self.size
        pixelsx = max(1200, size[0])
        pixelsy = int(pixelsx*size[1]/size[0])
        imagesize = (pixelsx, pixelsy)
        image = QImage(pixelsx,
                       pixelsy,
                       QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.white)
        painter.drawRect(QRect(0, 0, *imagesize))

        targetrect = QRectF(0, 0, *imagesize)
        sourcerect = QRectF(0, 0, *size)
        self.render(painter, targetrect, sourcerect)
        painter.end()

        return image.save(fn)
Example #11
0
    def saveAsPdf(self, fn, force=False):
        """
        Save bar image as a eps file.

        Args:
            fn: Filename
            force: if True, overwrites an existing file. If false, raises a
            RuntimeError if file already exists.
        """
        printer = QPrinter(QPrinter.HighResolution)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(fn)
        printer.setFullPage(True)
        printer.setPageSize(QPrinter.Custom)
        printer.setPaperSize(QSizeF(*self.size), QPrinter.Millimeter)
        printer.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter)

        painter = QPainter(printer)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.white)
        painter.drawRect(QRect(0, 0, *self.size))

        targetrect = QRectF(0, 0, printer.width(), printer.height())
        sourcerect = QRectF(0, 0, *self.size)
        self.render(painter, targetrect, sourcerect)
        painter.end()
        return True
Example #12
0
 def paintEvent(self, e):
     painter = QPainter(self.viewport())
     pen = painter.pen()
     pen.setCosmetic(True)
     pen.setWidth(0.0)
     painter.setPen(pen)
     painter.setRenderHint(QPainter.Antialiasing, False)
     groups = self.document().rootFrame().childFrames()
     for group in groups:
         h = QtReduceRowFormat().leftMargin()
         hoff = int(0.4 * h)
         self.__drawFrameBracket(painter,
                                 group,
                                 hoff,
                                 QColor(qRgb(0x80, 0x80, 0x80)),
                                 xt=2)
         childFrames = group.childFrames()
         hoff = int(0.7 * h)
         self.__drawFrameBracket(painter,
                                 childFrames[0],
                                 hoff,
                                 QColor(qRgb(0xb0, 0x70, 0x70)),
                                 xt=2)
         self.__drawFrameBracket(painter,
                                 childFrames[1],
                                 hoff,
                                 QColor(qRgb(0x70, 0x70, 0xb0)),
                                 xt=2)
     painter.end()
     super(QtReduceFrameView, self).paintEvent(e)
Example #13
0
    def paintEvent(self, e):
        painter = QPainter()
        painter.begin(self)
        
        width = self.width()
        height = self.height()
        
        #Blank out the world
        painter.fillRect(0, 0, width, height, Qt.white)

        #Compute width/height of the columns and rows
        
        #Reserve pixels for the grid lines
        colWidth = (width - (self._NUM_COLS - 1) * self._GRID_SIZE) / self._NUM_COLS
        rowHeight = (height - (self._NUM_ROWS - 1) * self._GRID_SIZE) / self._NUM_ROWS
        
        colWidth = max(1, colWidth)
        rowHeight = max(1, rowHeight)

        #Perform drawing operations for world rendering
        self._drawGrid(width, height, colWidth, rowHeight, painter)
        self._drawObstacles(colWidth, rowHeight, painter)
        if self._drawVisited:
            self._drawVisitedCells(colWidth, rowHeight, painter)
        if self._drawActive:
            self._drawActiveCells(colWidth, rowHeight, painter)
        self._drawStartAndEndCells(colWidth, rowHeight, painter)
        self._drawCurrentCell(colWidth, rowHeight, painter)
        if self._drawCheapestPath:
            self._drawPath(colWidth, rowHeight, painter)
        
        painter.end()
Example #14
0
 def paintEvent(self, event):
     contents_y = self.edit.verticalScrollBar().value()
     page_bottom = contents_y + self.edit.viewport().height()
     font_metrics = self.fontMetrics()
     current_block = self.edit.document().findBlock(
         self.edit.textCursor().position())
     painter = QPainter(self)
     line_count = 0
     block = self.edit.document().begin()
     while block.isValid():
         line_count += 1
         position = self.edit.document().documentLayout().blockBoundingRect(
             block).topLeft()
         if position.y() > page_bottom:
             break
         bold = False
         if block == current_block:
             bold = True
             font = painter.font()
             font.setBold(True)
             painter.setFont(font)
             self.current = line_count
         painter.drawText(
             self.width() - font_metrics.width(str(line_count)) - 10,
             round(position.y()) - contents_y + font_metrics.ascent(),
             str(line_count))
         if bold:
             font = painter.font()
             font.setBold(False)
             painter.setFont(font)
         block = block.next()
     self.highest_line = line_count
     painter.end()
     QWidget.paintEvent(self, event)
Example #15
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.HighQualityAntialiasing)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.SmoothPixmapTransform)
     # change the look for on/off
     if self.isChecked():
         # blue fill
         brush = QBrush(self.color1)
         painter.setBrush(brush)
         painter.drawRoundedRect(0, 7, self.width() - 2, self.height() - 15, self.height() / 2 - 10,
                                 self.height() / 2)
         brush = QBrush(self.lighter(self.color1))
         painter.setBrush(brush)
         painter.drawEllipse(self.width() - self.height(), 0, self.height(), self.height())
     else:
         # gray fill
         brush = QBrush(self.color2)
         painter.setBrush(brush)
         painter.drawRoundedRect(1, 7, self.width() - 3, self.height() - 15, self.height() / 2 - 10,
                                 self.height() / 2)
         brush = QBrush(QColor(100, 100, 100))
         painter.setBrush(brush)
         painter.drawEllipse(0, 0, self.height(), self.height())
     painter.end()
Example #16
0
    def paint(self, canvas, is_secondary_color=False, additional_flag=False):
        pen = QPen()
        pen.setWidth(self.data_singleton.pen_size)
        pen.setStyle(Qt.SolidLine)
        pen.setCapStyle(Qt.RoundCap)
        pen.setJoinStyle(Qt.RoundJoin)

        if is_secondary_color:
            pen.setBrush(self.data_singleton.secondary_color)
        else:
            pen.setBrush(self.data_singleton.primary_color)

        painter = QPainter(canvas.image)
        painter.setPen(pen)

        if self._start_point != self._end_point:
            painter.drawLine(self._start_point, self._end_point)

        if self._start_point == self._end_point:
            painter.drawPoint(self._start_point)

        painter.end()

        canvas.edited = True
        canvas.update()
Example #17
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.HighQualityAntialiasing)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.SmoothPixmapTransform)
     # change the look for on/off
     if self.isChecked():
         # blue fill
         brush = QBrush(self.color1)
         painter.setBrush(brush)
         painter.drawRoundedRect(0, 7,
                                 self.width() - 2,
                                 self.height() - 15,
                                 self.height() / 2 - 10,
                                 self.height() / 2)
         brush = QBrush(self.lighter(self.color1))
         painter.setBrush(brush)
         painter.drawEllipse(self.width() - self.height(), 0, self.height(),
                             self.height())
     else:
         # gray fill
         brush = QBrush(self.color2)
         painter.setBrush(brush)
         painter.drawRoundedRect(1, 7,
                                 self.width() - 3,
                                 self.height() - 15,
                                 self.height() / 2 - 10,
                                 self.height() / 2)
         brush = QBrush(QColor(100, 100, 100))
         painter.setBrush(brush)
         painter.drawEllipse(0, 0, self.height(), self.height())
     painter.end()
Example #18
0
    def save_image_to(self, path):

        TOP_MARGIN = 50
        LEFT_MARGIN = 50

        # Determine the size of the entire graph
        graph_size = self._graph_size()

        image_size = QSize(graph_size.width() + LEFT_MARGIN * 2,
                           graph_size.height() + TOP_MARGIN * 2
                           )

        image = QImage(image_size, QImage.Format_ARGB32)
        image.fill(Qt.white)  # white background

        painter = QPainter(image)
        painter.translate(TOP_MARGIN, LEFT_MARGIN)
        painter.setRenderHint(QPainter.TextAntialiasing)
        self._paint(painter,
                    QPoint(-TOP_MARGIN, -LEFT_MARGIN),
                    QPoint(image_size.width(), image_size.height())
                    )
        painter.end()

        image.save(path)
Example #19
0
def SetImageTransparency(image, transparencyPercentage):
    """ Set the Image Transparency to the value provided """
    alpha = QImage(image)
    painter = QPainter(alpha)
    alphaValue = int(transparencyPercentage * 255 / 100)
    painter.fillRect(alpha.rect(), QColor(alphaValue, alphaValue, alphaValue))
    painter.end()
    image.setAlphaChannel(alpha)
Example #20
0
 def paint(self, painter, option, widget=None):
     painter_inverted = QPainter()
     brect= QGraphicsProxyWidget.boundingRect(self)
     invertedColor = QImage(brect.width(),brect.height(),QImage.Format_RGB32)
     painter_inverted.begin(invertedColor)
     QGraphicsProxyWidget.paint(self,painter_inverted, option, widget)
     painter_inverted.end()
     painter.drawImage(0,0,invertedColor.rgbSwapped())
Example #21
0
def SetImageTransparency(image, transparencyPercentage):
    """ Set the Image Transparency to the value provided """
    alpha = QImage(image)
    painter = QPainter(alpha)
    alphaValue = int(transparencyPercentage*255/100)
    painter.fillRect(alpha.rect(), QColor(alphaValue, alphaValue, alphaValue))
    painter.end()
    image.setAlphaChannel(alpha)
Example #22
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     qp.setRenderHint(QPainter.Antialiasing)
     self._draw_rim(event, qp)
     self._draw_slices(event, qp)
     self._draw_indicator(event, qp)
     qp.end()
Example #23
0
 def paintEvent(self, event):
     qp = QPainter()
     qp.begin(self)
     qp.setRenderHint(QPainter.Antialiasing)
     self._draw_rim(event, qp)
     self._draw_slices(event, qp)
     self._draw_indicator(event, qp)
     qp.end()
Example #24
0
    def numberbarPaint(self, number_bar, event):
        """Paints the line numbers of the code file"""
        self.number_bar.link = []
        font_metrics = self.getWidget().fontMetrics()
        current_line = self.getWidget().document().findBlock(
            self.getWidget().textCursor().position()).blockNumber() + 1

        block = self.getWidget().firstVisibleBlock()
        line_count = block.blockNumber()
        painter = QPainter(self.number_bar)
        # TODO: second argument is color -> to settings
        painter.fillRect(self.number_bar.rect(),
                         self.getWidget().palette().base())

        # Iterate over all visible text blocks in the document.
        while block.isValid():
            line_count += 1
            text = str(line_count)
            block_top = self.getWidget().blockBoundingGeometry(
                block).translated(self.getWidget().contentOffset()).top()
            if not block.isVisible():
                block = block.next()
                while not block.isVisible():
                    line_count += 1
                    block = block.next()
                continue
            self.number_bar.link.append((block_top, line_count))
            # Check if the position of the block is out side of the visible
            # area.
            if block_top >= event.rect().bottom():
                break

            # We want the line number for the selected line to be bold.
            if line_count == current_line:
                font = painter.font()
                font.setBold(True)

            else:
                font = painter.font()
                font.setBold(False)
            # line opens a block
            if line_count in self.hidden:
                text += "+"
                font.setUnderline(True)
            elif block.text().count("(") > block.text().count(")"):
                text += "-"
                font.setUnderline(True)
            else:
                font.setUnderline(False)
            painter.setFont(font)
            # Draw the line number right justified at the position of the
            # line.
            paint_rect = QRect(0, block_top, self.number_bar.width(),
                               font_metrics.height())
            painter.drawText(paint_rect, Qt.AlignLeft, text)
            block = block.next()

        painter.end()
Example #25
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.HighQualityAntialiasing)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.SmoothPixmapTransform)
     painter.setBrush(QColor(self.color))
     painter.drawRect(self.window().x() + 4, self.window().y() + 4, self.window().width(), self._height)
     painter.end()
Example #26
0
    def paintEvent(self, event):

        painter = QPainter()

        painter.begin(self)

        self.drawWidget(painter)

        painter.end()
Example #27
0
    def capture(self, filename):
        image = QImage(self._view.page().currentFrame().contentsSize(), QImage.Format_ARGB32)

        painter = QPainter(image)

        self._view.page().currentFrame().render(painter)
        painter.end()

        image.save(filename)
Example #28
0
 def _update_cursor(self):
     x = self.diameter
     w, h = x, x
     pixmap = QPixmap(w, h)
     pixmap.fill(Qt.transparent)
     p = QPainter(pixmap)
     p.drawPoints(self._points)
     p.end()
     self._cursor_pixmap = pixmap.createMaskFromColor(Qt.transparent)
    def paintEvent(self, event):
        text = []
        text.append(['{0}; {1}'.format(self.parent.chunkData['X'], self.parent.chunkData['Y']), Qt.black])
        if self.parent.chunkData[14] > 0:
            text.append(['Gold = {0}'.format(self.parent.chunkData[14]), Qt.yellow])
        else:
            text.append(['', Qt.yellow])
        if self.parent.chunkData[15] > 0:
            text.append(['Iron = {0}'.format(self.parent.chunkData[15]), Qt.red])
        else:
            text.append(['', Qt.red])
        if self.parent.chunkData[56] > 0:
            text.append(['Diamond = {0}'.format(self.parent.chunkData[56]), Qt.cyan])
        else:
            text.append(['', Qt.cyan])
        if self.parent.chunkData[73] > 0:
            text.append(['Redstone = {0}'.format(self.parent.chunkData[73]), Qt.magenta])
        else:
            text.append(['', Qt.magenta])
        if self.parent.chunkData[49] > 0:
            text.append(['Obsidian = {0}'.format(self.parent.chunkData[49]), Qt.darkYellow])
        else:
            text.append(['', Qt.darkYellow])
        if self.parent.chunkData[21] > 0:
            text.append(['Lazurit = {0}'.format(self.parent.chunkData[21]), Qt.darkBlue])
        else:
            text.append(['', Qt.darkBlue])

        painter = QPainter()
        painter.begin(self)

        painter.drawRect(self.parent.leftMargin, self.parent.topMargin,
                         self.edgeLen, self.edgeLen)

        cX = self.parent.leftMargin + self.parent.vsepara
        cY = self.parent.topMargin + self.parent.hsepara

        alig = Qt.AlignCenter
        i = 0
        fontik = painter.font()
        for t in text:
            if i > 0:
                alig = Qt.AlignLeft
            painter.setPen(t[1])
            if i == 2:
                fontik.setUnderline(True)
            else:
                fontik.setUnderline(False)
            painter.setFont(fontik)
            painter.drawText(cX, cY, self.tBoxWidth, self.tBoxHeight, alig, t[0])
            cY += self.lineSpacing
            i += 1
            

        painter.end()
        del painter
Example #30
0
	def paintEvent(self, event):
		painter = QPainter()

		painter.begin(self)

		self.theme.render(painter, "kdiamond-" + self.color)
		if self.selected:
			self.theme.render(painter, "kdiamond-selection")

		painter.end()
Example #31
0
    def print_(self):
        canvas = self.mw.get_current_canvas()
        if not canvas:
            return

        printer = QPrinter()
        dlg = QPrintDialog(printer, self.mw)
        if dlg.exec_() == QDialog.Accepted:
            painter = QPainter(printer)
            painter.drawImage(0, 0, canvas.image)
            painter.end()
Example #32
0
 def paintEvent(self, e):
     ''' overwrite paintEvent in order to also redraw points (indicating
     electrode positions) and their link to added plots
     
     this is necessary to get smooth animation if plots are dragged around
     '''
     super(DragWindow, self).paintEvent(e)
     qp = QPainter()
     qp.begin(self)
     self.drawPoints(qp)
     qp.end()
Example #33
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.HighQualityAntialiasing)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.SmoothPixmapTransform)
     painter.setBrush(QColor(self.color))
     painter.drawRect(self.window().x() + 4,
                      self.window().y() + 4,
                      self.window().width(), self._height)
     painter.end()
Example #34
0
    def capture_pdf(self):
        printer = QPrinter(QPrinter.HighResolution)
        printer.setResolution(300)
        printer.setOutputFileName("QtPrinter.pdf")
        printer.setPaperSize(QPrinter.A4)
        printer.setOrientation(QPrinter.Landscape)
        printer.setOutputFormat(QPrinter.PdfFormat)

        painter = QPainter(printer)
        self.main_frame.render(painter)
        painter.end()
Example #35
0
    def print_(self):
        canvas = self.mw.get_current_canvas()
        if not canvas:
            return

        printer = QPrinter()
        dlg = QPrintDialog(printer, self.mw)
        if dlg.exec_() == QDialog.Accepted:
            painter = QPainter(printer)
            painter.drawImage(0, 0, canvas.image)
            painter.end()
Example #36
0
    def paintEvent(self, evt):
        # print 'paint', self.color, self.text(), self.width(), self.height(), evt.rect().width()
        qp = QPainter()
        qp.begin(self)
        qp.setBrush(QColor('#{}'.format(self.color[:-2])))
        qp.drawRect(0, 0, self.width(), self.height())
        qp.end()

        qp.begin(self)
        qp.setPen(self._get_text_color())
        qp.drawText(evt.rect(), QtCore.Qt.AlignCenter, self.text())
        qp.end()
Example #37
0
 def __init__(self, parent=None):
     self.hamburger = QImage(128, 128, QImage.Format_ARGB32)
     QPushButton.__init__(self, parent)
     self.svgrenderer = QSvgRenderer("icons\\hamburger.svg")
     paint = QPainter(self.hamburger)
     paint.setRenderHint(QPainter.HighQualityAntialiasing)
     paint.setRenderHint(QPainter.SmoothPixmapTransform)
     self.svgrenderer.render(paint)
     paint.end()
     pixmap = QPixmap()
     self.setIcon(QIcon(pixmap.fromImage(self.hamburger)))
     self.setStyleSheet("QPushButton, QPushButton:pressed{background-color: rgba(0,0,0,0)} QPushButton:hover {background-color: rgba(255,255,255,100); border-radius: 32px} ")
Example #38
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.HighQualityAntialiasing)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.SmoothPixmapTransform)
     painter.setBrush(self.color)
     if self.effect_size == self.radius:
         painter.drawEllipse(1, 1, self.radius - 1, self.radius - 1)
         painter.drawPixmap(QRect(14, 14, self.radius / 2, self.radius / 2), self.pixmap)
     else:
         painter.drawEllipse(self.width() / 2, self.height() / 2, self.effect_size, self.effect_size)
     painter.end()
Example #39
0
    def paintEvent(self, event):
        cX = self.parent.leftMargin + self.scaleMarkLen
        cY = self.parent.topMargin + self.scaleMarkLen
        worldX = self.parent.chunkX*16
        worldZ = self.parent.chunkZ*16
        painter = QPainter()
        path = QPainterPath()
        painter.begin(self)
        painter.save()
        #painter.setFont(QFont('Arial Narrow', 8)) #QFont.Bold
        # draw scale
        x = cX
        y = cY
        painter.rotate(-90)
        for i in range(16):
            fr = QRectF(-y, x, self.scaleMarkLen, self.edgeLen)
            painter.drawText(fr, Qt.AlignHCenter | Qt.AlignVCenter, '-5555')
            painter.drawRect(fr)
            #fr = QRectF(-y - 16*self.edgeLen - self.scaleMarkLen, x, self.scaleMarkLen, self.edgeLen)
            #painter.drawText(fr, Qt.AlignHCenter | Qt.AlignVCenter, '-5555')
            #painter.drawRect(fr)
            x += self.edgeLen
        painter.rotate(90)

        x = self.parent.leftMargin
        y = cY
        for i in range(16):
            fr = QRectF(x, y, self.scaleMarkLen, self.edgeLen)
            painter.drawText(fr, Qt.AlignHCenter | Qt.AlignVCenter, '-5555')
            painter.drawRect(fr)
            #fr = QRectF(x + self.scaleMarkLen + 16*self.edgeLen, y, self.scaleMarkLen, self.edgeLen)
            #painter.drawText(fr, Qt.AlignHCenter | Qt.AlignVCenter, '-5555')
            #painter.drawRect(fr)
            y += self.edgeLen

        x = cX
        y = cY
        for i in range(16):
            for j in range(16):
                path.addRect(x, y, self.edgeLen, self.edgeLen)
                fr = QRectF(x, y, self.edgeLen, self.edgeLen)
                #painter.drawText(fr, Qt.AlignHCenter | Qt.AlignVCenter, '-5555')
                x += self.edgeLen
            x = cX
            y += self.edgeLen

        painter.drawPath(path)

        painter.restore()
        painter.end()
        del painter
Example #40
0
    def drawIconWithShadow(icon, rect, p, iconMode, radius, color, offset):
        cache = QPixmap()
        pixmapName = "icon {0} {1} {2}".format(icon.cacheKey(), iconMode, rect.height())

        if not QPixmapCache.find(pixmapName, cache):
            px = icon.pixmap(rect.size())
            cache = QPixmap(px.size() + QSize(radius * 2, radius * 2))
            cache.fill(Qt.transparent)

            cachePainter = QPainter(cache)
            if iconMode == QIcon.Disabled:
                im = px.toImage().convertToFormat(QImage.Format_ARGB32)
                for y in range(im.height()):
                    scanLine = im.scanLine(y)
                    for x in range(im.width()):
                        pixel = scanLine
                        intensity = qGray(pixel)
                        scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel))
                        scanLine += 1
                px = QPixmap.fromImage(im)

            # Draw shadow
            tmp = QImage(px.size() + QSize(radius * 2, radius * 2 + 1), QImage.Format_ARGB32_Premultiplied)
            tmp.fill(Qt.transparent)

            tmpPainter = QPainter(tmp)
            tmpPainter.setCompositionMode(QPainter.CompositionMode_Source)
            tmpPainter.drawPixmap(QPoint(radius, radius), px)
            tmpPainter.end()

            # blur the alpha channel
            blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied)
            blurred.fill(Qt.transparent)
            blurPainter = QPainter(blurred)
            # todo : blur image
            blurPainter.end()

            tmp = blurred

            # blacken the image
            tmpPainter.begin(tmp)
            tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn)
            tmpPainter.fillRect(tmp.rect(), color)
            tmpPainter.end()

            tmpPainter.begin(tmp)
            tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn)
            tmpPainter.fillRect(tmp.rect(), color)
            tmpPainter.end()

            # draw the blurred drop shadow...
            cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp)

            # Draw the actual pixmap...
            cachePainter.drawPixmap(QPoint(radius, radius) + offset, px)
            QPixmapCache.insert(pixmapName, cache)

        targetRect = cache.rect()
        targetRect.moveCenter(rect.center())
        p.drawPixmap(targetRect.topLeft() - offset, cache)
 def takeScreenshot(self):
     [x, y, width, height] = self.image_crop
     frame = self.page().mainFrame()
     size = frame.contentsSize()
     size.setWidth(1000)
     size.setHeight(2000)
     self.page().setViewportSize(size)
     image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
     painter = QPainter(image)
     frame.render(painter)
     painter.end()
     image1 = image.copy(x, y, width, height)
     image1.save(self.fileName)
     self.finished = True
Example #42
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     
     for widget in self._widgets:
         painter.translate(widget.x(),widget.y()) # move the painter to the widget's coordinates
         painter.setClipRect(0,0,widget.width(),widget.height()) # restrict the painting area
         
         widget._paint(painter) # paint the widget
         
         painter.translate(-widget.x(),-widget.y()) # get the painter ready for the next widget 
         painter.setClipRect(self.rect())           #  to be painted
         
     painter.end()
    def paintEvent(self, event):
        QPushButton.paintEvent(self, event)

        qp = QPainter()
        qp.begin(self)

        font = qp.font()
        font.setPixelSize(8)
        font.setWeight(QFont.Normal)
        qp.setFont(font)

        qp.drawText(event.rect().translated(1, 1), str(self._atomic_number))

        qp.end()
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        c = QColor()
        c.setNamedColor(self._window_bgcolor)

        h, s, l, a = c.getHsl()
        c.setHsl(h, s, 100, a)

        pen = QPen(c, 8, QtCore.Qt.SolidLine)
        qp.setPen(pen)

        qp.drawRoundedRect(event.rect(), 12, 12)
        qp.end()
 def takeScreenshot(self):        
     [x,y,width,height] = self.image_crop
     frame = self.page().mainFrame()
     size = frame.contentsSize()
     size.setWidth(1000)
     size.setHeight(2000)
     self.page().setViewportSize(size)
     image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
     painter = QPainter(image)
     frame.render(painter)
     painter.end()
     image1 = image.copy(x,y,width,height)
     image1.save(self.fileName)
     self.finished = True
Example #46
0
 def __init__(self, parent=None):
     self.hamburger = QImage(128, 128, QImage.Format_ARGB32)
     QPushButton.__init__(self, parent)
     self.svgrenderer = QSvgRenderer("icons\\hamburger.svg")
     paint = QPainter(self.hamburger)
     paint.setRenderHint(QPainter.HighQualityAntialiasing)
     paint.setRenderHint(QPainter.SmoothPixmapTransform)
     self.svgrenderer.render(paint)
     paint.end()
     pixmap = QPixmap()
     self.setIcon(QIcon(pixmap.fromImage(self.hamburger)))
     self.setStyleSheet(
         "QPushButton, QPushButton:pressed{background-color: rgba(0,0,0,0)} QPushButton:hover {background-color: rgba(255,255,255,100); border-radius: 32px} "
     )
Example #47
0
    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)

        colour = self._colour
        if not self._lit:
            colour = self._colour.darker(300)
        painter.setPen(QPen(Qt.black, 1))
        painter.setBrush(QBrush(colour))

        rect = event.rect()
        radius = min(rect.width(), rect.height()) / 3
        painter.drawEllipse(rect.center(), radius, radius)

        painter.end()
Example #48
0
    def saveAsPDF(self):
        '''Save plot as a PDF'''
        if not self.control.hasPlot:
            error.showMessage('Cannot save.. there is no data to save yet')
            return
        filter = 'PDF Documents (*.pdf);;All (*)'
        d = '' if self.pdfName is None else self.pdfName
        s = QFileDialog.getSaveFileName(self, 'PDF File Name',
                                              d, filter)
        # Continue unless the user hit cancel
        if not s[0]:
            return
        self.pdfName = s[0]

        # Set up the PDF printer
        printer = QPrinter()
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOrientation(QPrinter.Landscape)
        printer.setOutputFileName(self.pdfName)
        printer.setCreator('RAPID')

        # Send to the plot for printing
        p = QPainter()
        p.begin(printer)
        x, y = self.plot.calculatedData()
        plt = pgplot(x, y,
                     antialias=True,
                     connect='all',
                     pen={'color': 'b', 'width': 0})
        plt.setLabel('bottom', "Frequency (Wavenumbers, cm<sup>-1</sup>)")
        plt.getAxis('bottom').setPen('k')
        plt.setLabel('left', "Intensity (Normalized)")
        plt.getAxis('left').setPen('k')
        plt.setYRange(0, 1.1, padding=0)
        plt.invertX(self.plot.reversed)
        plt.setBackground('w')  # White

        # The raw (experimental) data, if any
        if self.plot.rawData is not None:
            data = self.plot.getRawData()
            x, y = data[:,0], data[:,1]
            curve2 = PlotCurveItem(x, y,
                                   antialias=True,
                                   connect='all',
                                   pen={'color': 'g', 'width': 0})
            plt.addItem(curve2)
        plt.render(p)
        p.end()
Example #49
0
def svg2icon(path, img_type=QImage):
    img = QImage(64, 64, QImage.Format_ARGB32)
    svgrenderer = QSvgRenderer(path)
    paint = QPainter(img)
    paint.setRenderHint(QPainter.HighQualityAntialiasing)
    paint.setRenderHint(QPainter.SmoothPixmapTransform)
    paint.setBrush(QColor(255, 255, 255, 255))
    paint.drawRect(QRect(-1, -1, 65, 65))
    svgrenderer.render(paint)
    paint.end()
    if img_type == QImage:
        return img
    elif img_type == QPixmap:
        pix = QPixmap
        pix = pix.fromImage(img)
        return pix
Example #50
0
    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)

        if self._lit:
            self._colour.setAlphaF(1)
        else:
            self._colour.setAlphaF(.25)
        painter.setPen(QPen(self._colour, 1))
        painter.setBrush(QBrush(self._colour))

        rect = event.rect()
        radius = min(rect.width(), rect.height()) / 3
        painter.drawEllipse(rect.center(), radius, radius)

        painter.end()
Example #51
0
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.setRenderHint(QPainter.HighQualityAntialiasing)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setRenderHint(QPainter.SmoothPixmapTransform)
     painter.setBrush(self.color)
     if self.effect_size == self.radius:
         painter.drawEllipse(1, 1, self.radius - 1, self.radius - 1)
         painter.drawPixmap(QRect(14, 14, self.radius / 2, self.radius / 2),
                            self.pixmap)
     else:
         painter.drawEllipse(self.width() / 2,
                             self.height() / 2, self.effect_size,
                             self.effect_size)
     painter.end()
Example #52
0
def svg2icon(path, img_type=QImage):
    img = QImage(64, 64, QImage.Format_ARGB32)
    svgrenderer = QSvgRenderer(path)
    paint = QPainter(img)
    paint.setRenderHint(QPainter.HighQualityAntialiasing)
    paint.setRenderHint(QPainter.SmoothPixmapTransform)
    paint.setBrush(QColor(255, 255, 255, 255))
    paint.drawRect(QRect(-1, -1, 65, 65))
    svgrenderer.render(paint)
    paint.end()
    if img_type == QImage:
        return img
    elif img_type == QPixmap:
        pix = QPixmap
        pix = pix.fromImage(img)
        return pix
Example #53
0
        def _numberbar_paint(self, number_bar, event):
            '''Paint number bar.'''

            font_metrics = self.fontMetrics()
            current_line = self.edit.document().findBlock(
                self.edit.textCursor().position()
            ).blockNumber() + 1

            block = self.edit.firstVisibleBlock()
            line_count = block.blockNumber()
            painter = QPainter(number_bar)
            painter.fillRect(event.rect(), self.palette().base())

            # Iterate over all visible text blocks in the document.
            while block.isValid():
                line_count += 1
                block_top = self.edit.blockBoundingGeometry(block).\
                    translated(self.edit.contentOffset()).top()

                # Check if the position of the block is out side of the visible
                # area.
                if not block.isVisible() or block_top >= event.rect().bottom():
                    break

                # We want the line number for the selected line to be bold.
                if line_count == current_line:
                    font = painter.font()
                    font.setBold(True)
                    font.setUnderline(True)
                    painter.setFont(font)
                else:
                    font = painter.font()
                    font.setBold(False)
                    font.setUnderline(False)
                    painter.setFont(font)

                # Draw the line number right justified at the position of the
                # line.
                paint_rect = QRect(0, block_top, number_bar.width(),
                                   font_metrics.height())
                painter.drawText(paint_rect, Qt.AlignRight,
                                 "{} ".format(unicode(line_count)))

                block = block.next()

            painter.end()
            return
Example #54
0
    def paint(self, painter, option, widget=None):
        """@reimp @public
    virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0)
    """
        #Q_UNUSED(option)
        #Q_UNUSED(widget)
        d = self.__d
        key = d.hash
        pm = QPixmap()
        if not QPixmapCache.find(key, pm):
            # Set up a convenient path
            path = QPainterPath()
            path.setFillRule(Qt.OddEvenFill)
            path.addEllipse(QPointF(d.actualOuterRadius, d.actualOuterRadius),
                            d.actualOuterRadius, d.actualOuterRadius)
            path.addEllipse(QPointF(d.actualOuterRadius, d.actualOuterRadius),
                            d.actualInnerRadius, d.actualInnerRadius)

            nActualDiameter = 2.0 * d.actualOuterRadius
            pm = QPixmap(nActualDiameter, nActualDiameter)
            pm.fill(Qt.transparent)
            p = QPainter(pm)

            # Draw the ring background
            p.setPen(Qt.NoPen)
            p.setBrush(d.backgroundColor)
            p.setRenderHint(QPainter.Antialiasing)
            p.drawPath(path)

            # Draw the ring foreground
            # TODO: Expose this gradient as Qml Property
            gradient = QConicalGradient(d.actualOuterRadius,
                                        d.actualOuterRadius, 0.0)
            gradient.setColorAt(0.0, Qt.transparent)
            gradient.setColorAt(0.05, d.foregroundColor)
            gradient.setColorAt(0.8, Qt.transparent)

            p.setBrush(gradient)
            p.drawPath(path)
            p.end()

            QPixmapCache.insert(key, pm)

        # Draw pixmap at center of item
        w, h = self.width(), self.height()
        sz = min(w, h)
        painter.drawPixmap(0.5 * (w - sz), 0.5 * (h - sz), pm)
Example #55
0
    def createPixmap(self):
        """Creates the pixmap shown when this label is dragged."""
        font_metric = QFontMetrics(QFont())
        text_size = font_metric.size(Qt.TextSingleLine, self.text)
        image = QImage(text_size.width() + 4,
                       text_size.height() + 4,
                       QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(240, 240, 120, 255))

        painter = QPainter()
        painter.begin(image)
        painter.setFont(QFont())
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(2, 2), text_size), Qt.AlignCenter,
                         self.text)
        painter.end()
        return image
Example #56
0
def gradientpixmap(pm):
  """
  @param  pm  QPixmap
  @return  QPixmap
  """
  # http://www.qtcentre.org/threads/4246-QGraphicsPixmapItem-modifying-the-alpha-channel-of-a-QPixmap
  # http://www.qtcentre.org/threads/37866-QPainter-fill-rect-with-gradient
  if not pm.isNull():
    w = pm.width()
    h = pm.height()
    if w and h:
      gr = getgradient(0, 0, w, h)
      #gr = QLinearGradient(alpha.rect().topLeft(), alpha.rect().bottomRight())
      alpha = QPixmap(w, h)
      p = QPainter(alpha)
      p.fillRect(alpha.rect(), gr)
      p.end()
      pm.setAlphaChannel(alpha)
Example #57
0
    def paintEvent(self, event):
        width = event.rect().width() - 1
        scale = float(width) / self._sizeValue.width()

        self._fontCurrent.setPointSizeF(scale * self.WEIGHT_CURRENT * 10)
        self._fontValue.setPointSizeF(scale * self.WEIGHT_VALUE * 10)
        self._fontRange.setPointSizeF(scale * self.WEIGHT_RANGE * 10)

        painter = QPainter()
        painter.begin(self)
        painter.setPen(QPen(QColor(42, 67, 107), 4 * scale))

        pos = self.__drawText(painter, scale)
        pos = self.__drawBar(painter, scale, width, pos)

        painter.end()

        self.setMinimumHeight(pos)
Example #58
0
    def __init__(self, *args):
        super(CheckBox, self).__init__(*args)
        self.setMouseTracking(True)
        if tuple() in [type(i) for i in args]:
            for arg in args:
                if isinstance(arg) == tuple():
                    color = arg
        else:
            color = (QColor(0, 150, 136), QColor(255, 255, 255))
        self.color1 = color[0]
        self.color2 = color[1]
        self.svgrenderer = QSvgRenderer("icons\\check.svg")

        self.check = QImage(500, 200, QImage.Format_ARGB32)
        self.resize(30, 30)
        paint = QPainter(self.check)
        self.svgrenderer.render(paint)
        paint.end()