Exemplo n.º 1
0
	def paintEvent(self, paintEvent):
		painter = QPainter(self)
		painter.setClipRect(paintEvent.rect())

		color = self.__editor.palette().text()
		painter.setPen(QPen(color, self.__lineWidth))
		painter.drawRect(self.rect())
Exemplo n.º 2
0
    def paint(self, painter: QPainter, option: 'QStyleOptionViewItem',
              index: QModelIndex) -> None:
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter_box_rect = option.rect.marginsRemoved(QMargins(1, 1, 1, 1))
        painter_pix_rect = option.rect.marginsRemoved(QMargins(10, 10, 10, 10))
        try:
            painter.save()
            try:
                painter.setClipRect(painter_box_rect, Qt.IntersectClip)
                if option.state & QStyle.State_Selected:
                    painter.fillRect(painter_box_rect,
                                     option.palette.highlight())
                    painter.setPen(option.palette.highlight().color())
                else:
                    painter.setPen(option.palette.alternateBase().color())
                painter.drawRect(painter_box_rect)
            finally:
                painter.restore()
            try:
                pix = self._get_media_pixmap(index.data(), option,
                                             painter_pix_rect.size())
            except Exception as ex:
                c = option.palette.text().color()
                c.setAlphaF(.15)
                painter.fillRect(painter_pix_rect,
                                 QBrush(c, Qt.DiagCrossPattern))

                if not isinstance(ex, KeyError):
                    import traceback
                    traceback.print_exc()
            else:
                painter.drawPixmap(painter_pix_rect, pix, pix.rect())
        except:
            import traceback
            traceback.print_exc()
Exemplo n.º 3
0
    def paintEvent(self, event):
        """Paints the board."""
        painter = QPainter(self)

        painter.setRenderHint(QPainter.Antialiasing, True)

        painter.setPen(QPen(Qt.black, Qt.SolidLine))
        painter.setBrush(QBrush(Qt.white, Qt.SolidPattern))

        painter.setClipRect(0, 0, self.canvas.width(), self.canvas.height())

        # background
        painter.drawRect(0, 0, self.canvas.width(), self.canvas.height())

        painter.translate(*self.translation)
        painter.scale(self.scale, self.scale)

        # draw vertexes
        for n1 in self.graph.get_nodes():
            for n2, weight in n1.get_neighbours().items():
                self.draw_vertex(n1, n2, weight, painter)

        # draw nodes
        for node in self.graph.get_nodes():
            self.draw_node(node, painter)
Exemplo n.º 4
0
    def paintEvent(self, e):
        painter = QPainter(self)

        # Draw empty button (no label or icon).
        buttonStyle = QStyleOptionButton()
        self.initStyleOption(buttonStyle)
        buttonStyle.text = ''
        buttonStyle.icon = QIcon()
        buttonStyle.iconSize = QSize(-1, -1)
        self.style().drawControl(QStyle.CE_PushButton, buttonStyle, painter, self)

        # Get button label style.
        labelStyle = QStyleOptionButton()
        self.initStyleOption(labelStyle)
        labelStyle.rect = self.style().subElementRect(QStyle.SE_PushButtonContents, labelStyle, self)

        # Clip everything we paint to label area.
        painter.setClipRect(labelStyle.rect)
        painter.setClipping(True)

        # TODO
        painter.translate(-200, 0); # Has to happen after we set clipping.

        # Draw label (optionally with icon), similar to how Qt does it (src/widgets/styles/qcommonstyle.cpp in Qt 5.3).
        self.style().drawControl(QStyle.CE_PushButtonLabel, labelStyle, painter, self)
Exemplo n.º 5
0
    def paintEvent(self, event):
        p = QPainter(self)

        if self.scrollEnabled:
            self.buffer.fill(qRgba(0, 0, 0, 0))
            pb = QPainter(self.buffer)
            pb.setPen(p.pen())
            pb.setFont(p.font())

            x = min(-self.scrollPos, 0) + self.leftMargin
            while x < self.width():
                pb.drawStaticText(
                    QPointF(x,
                            (self.height() - self.wholeTextSize.height()) / 2)
                    + QPoint(2, 2), self.staticText)
                x += self.wholeTextSize.width()

            #Apply Alpha Channel
            pb.setCompositionMode(QPainter.CompositionMode_DestinationIn)
            pb.setClipRect(self.width() - 15, 0, 15, self.height())
            pb.drawImage(0, 0, self.alphaChannel)
            pb.setClipRect(0, 0, 15, self.height())
            #initial situation: don't apply alpha channel in the left half of the image at all; apply it more and more until scrollPos gets positive
            if self.scrollPos < 0:
                pb.setOpacity((max(-8, self.scrollPos) + 8) / 8.0)
            pb.drawImage(0, 0, self.alphaChannel)

            p.drawImage(0, 0, self.buffer)
        else:
            x = (self.width() - self.wholeTextSize.width()) / 2
            y = (self.height() - self.wholeTextSize.height()) / 2
            p.drawStaticText(QPointF(x, y), self.staticText)
Exemplo n.º 6
0
    def paintEvent(self, ev):
        super(TagsLabelWidget, self).paintEvent(ev)

        painter = QPainter(self)

        painter.save()
        try:
            painter.setBackground(self.palette().brush(self.backgroundRole()))
            painter.eraseRect(ev.rect())

            painter.setClipRect(ev.rect())

            fm = QFontMetrics(self.font())  # TODO use style

            x = self.xmargin
            for sz, tag in self._positions(self.tags):
                fg, bg = tag_to_colors(tag)
                painter.setPen(fg.color())

                painter.fillRect(x, self.ymargin,
                                 sz.width() + 2 * self.xpadding, fm.height(),
                                 bg.color())
                painter.drawText(x + self.xpadding, self.ymargin + fm.ascent(),
                                 tag)
                x += sz.width() + self.xmargin + 2 * self.xpadding

        finally:
            painter.restore()
Exemplo n.º 7
0
    def paintEvent(self, event):
        content_rect = self.contentsRect()
        if self.spinner_size:
            size = min(self.spinner_size, content_rect.width(),
                       content_rect.height())
        else:
            size = min(content_rect.width(), content_rect.height())
        dot_count = 5
        dot_size = int(size / dot_count) * 1.5

        spinner_rect = QRect(content_rect.left(), content_rect.top(), size,
                             size)

        painter = QPainter(self)
        painter.setClipRect(content_rect)

        if self.timer_id:
            diff_height = content_rect.height() - size
            offs_y = 0
            if diff_height > 0:
                if self.vertical_align == Qt.AlignVCenter:
                    offs_y = diff_height / 2
                elif self.vertical_align == Qt.AlignBottom:
                    offs_y = diff_height

            x_center = spinner_rect.left(
            ) + spinner_rect.width() / 2 - dot_size / 2
            y_center = spinner_rect.top(
            ) + offs_y + spinner_rect.height() / 2 - dot_size / 2

            painter.save()
            for i in range(dot_count):
                if self.counter % dot_count == i:
                    painter.setBrush(QBrush(QColor(0, 0, 0)))
                    d_size = dot_size * 1.1
                else:
                    painter.setBrush(QBrush(QColor(200, 200, 200)))
                    d_size = dot_size

                r = size / 2 - dot_size / 2
                x = r * math.cos(2 * math.pi * i / dot_count)
                y = r * math.sin(2 * math.pi * i / dot_count)
                painter.drawEllipse(x_center + x, y_center + y, d_size, d_size)
            painter.restore()

        if self.message:
            # painter.setPen(QPen(Qt.black))
            if self.font_size:
                f = painter.font()
                f.setPointSize(self.font_size)
                painter.setFont(f)

            text_rect = QRect(content_rect)
            text_rect.translate(
                spinner_rect.width() +
                SpinnerWidget.SPINNER_TO_TEXT_DISTANCE if self.timer_id else 0,
                0)
            painter.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter,
                             self.message)
        painter.end()
Exemplo n.º 8
0
    def paintEvent(self, ev):
        color = self.palette().color(QPalette.Highlight)
        painter = QPainter(self)

        # Filled rectangle.
        painter.setClipRect(self.rect())
        color.setAlpha(50)
        painter.fillRect(self.rect().adjusted(2,2,-2,-2), color)

        # Thin rectangle outside.
        color.setAlpha(150)
        painter.setPen(color)
        painter.drawRect(self.rect().adjusted(0,0,-1,-1))

        # Pseudo-handles at the corners and sides
        color.setAlpha(100)
        pen = QPen(color)
        pen.setWidth(8)
        painter.setPen(pen)
        painter.setBackgroundMode(Qt.OpaqueMode)
        # Clip at 4 corners
        region = QRegion(QRect(0,0,20,20))
        region += QRect(self.rect().width()-20, 0, 20, 20)
        region += QRect(self.rect().width()-20, self.rect().height()-20, 20, 20)
        region += QRect(0, self.rect().height()-20, 20, 20)
        # Clip middles
        region += QRect(0, self.rect().height() // 2 - 10, self.rect().width(), 20)
        region += QRect(self.rect().width() // 2 - 10, 0, 20, self.rect().height())
        
        # Draw thicker rectangles, clipped at corners and sides.
        painter.setClipRegion(region)
        painter.drawRect(self.rect())
Exemplo n.º 9
0
 def _render_qwebpage_full(self, web_rect, render_rect, canvas_size):
     """Render web page in one step."""
     if self._qpainter_needs_tiling(render_rect, canvas_size):
         # If this condition is true, this function may get stuck.
         raise ValueError("Rendering region is too large to be drawn"
                          " in one step, use tile-by-tile renderer instead")
     canvas = QImage(canvas_size, self.qt_image_format)
     if self.is_jpeg():
         # White background for JPEG images, same as we have in all browsers.
         canvas.fill(Qt.white)
     else:
         # Preserve old behaviour for PNG format.
         canvas.fill(0)
     painter = QPainter(canvas)
     try:
         painter.setRenderHint(QPainter.Antialiasing, True)
         painter.setRenderHint(QPainter.TextAntialiasing, True)
         painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
         painter.setWindow(web_rect)
         painter.setViewport(render_rect)
         painter.setClipRect(web_rect)
         self.web_page.mainFrame().render(painter)
     finally:
         painter.end()
     return WrappedQImage(canvas)
Exemplo n.º 10
0
 def _render_qwebpage_full(self, web_rect, render_rect, canvas_size):
     """Render web page in one step."""
     if self._qpainter_needs_tiling(render_rect, canvas_size):
         # If this condition is true, this function may get stuck.
         raise ValueError("Rendering region is too large to be drawn"
                          " in one step, use tile-by-tile renderer instead")
     canvas = QImage(canvas_size, self.qt_image_format)
     if self.is_jpeg():
         # White background for JPEG images, same as we have in all browsers.
         canvas.fill(Qt.white)
     else:
         # Preserve old behaviour for PNG format.
         canvas.fill(0)
     painter = QPainter(canvas)
     try:
         painter.setRenderHint(QPainter.Antialiasing, True)
         painter.setRenderHint(QPainter.TextAntialiasing, True)
         painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
         painter.setWindow(web_rect)
         painter.setViewport(render_rect)
         painter.setClipRect(web_rect)
         self.web_page.mainFrame().render(painter)
     finally:
         painter.end()
     return WrappedQImage(canvas)
Exemplo n.º 11
0
    def paintEvent(self, ev):
        ### Paint code contributed by Richard Cognot Jun 2012
        color = self.palette().color(QPalette.Highlight)
        painter = QPainter(self)

        # Filled rectangle.
        painter.setClipRect(self.rect())
        color.setAlpha(50)
        painter.fillRect(self.rect().adjusted(2,2,-2,-2), color)

        # Thin rectangle outside.
        color.setAlpha(150)
        painter.setPen(color)
        painter.drawRect(self.rect().adjusted(0,0,-1,-1))

        # Pseudo-handles at the corners and sides
        color.setAlpha(100)
        pen = QPen(color)
        pen.setWidth(8)
        painter.setPen(pen)
        painter.setBackgroundMode(Qt.OpaqueMode)
        # Clip at 4 corners
        region = QRegion(QRect(0,0,20,20))
        region += QRect(self.rect().width()-20, 0, 20, 20)
        region += QRect(self.rect().width()-20, self.rect().height()-20, 20, 20)
        region += QRect(0, self.rect().height()-20, 20, 20)
        # Clip middles
        region += QRect(0, self.rect().height() // 2 - 10, self.rect().width(), 20)
        region += QRect(self.rect().width() // 2 - 10, 0, 20, self.rect().height())

        # Draw thicker rectangles, clipped at corners and sides.
        painter.setClipRegion(region)
        painter.drawRect(self.rect())
Exemplo n.º 12
0
 def _render_qwebpage_full(
     self,
     web_rect: QRect,
     render_rect: QRect,
     canvas_size: QSize,
 ) -> 'WrappedImage':
     """ Render web page in one step. """
     if self._qpainter_needs_tiling(render_rect, canvas_size):
         # If this condition is true, this function may get stuck.
         raise ValueError("Rendering region is too large to be drawn"
                          " in one step, use tile-by-tile renderer instead")
     canvas = self.img_converter.new_qimage(canvas_size)
     painter = QPainter(canvas)
     try:
         painter.setRenderHint(QPainter.Antialiasing, True)
         painter.setRenderHint(QPainter.TextAntialiasing, True)
         painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
         painter.setWindow(web_rect)
         painter.setViewport(render_rect)
         painter.setClipRect(web_rect)
         # self.web_page.mainFrame().render(painter)
         self.web_page.view().render(painter)
     finally:
         painter.end()
     return WrappedQImage(canvas)
Exemplo n.º 13
0
    def paintEvent(self, paintEvent):
        painter = QPainter(self)
        painter.setClipRect(paintEvent.rect())

        color = self.__editor.palette().text()
        painter.setPen(QPen(color, self.__lineWidth))
        painter.drawRect(self.rect())
Exemplo n.º 14
0
 def getPixmap(self):
     pixmap = QPixmap(self.width * self.pixelRatio,
                      self.height * self.pixelRatio)
     pixmap.setDevicePixelRatio(self.pixelRatio)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, self.height)
     painter.scale(1, -1)
     if self.headerAtBottom:
         bodyRect = (0, 0, self.width, self.height - self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     else:
         bodyRect = (0, 0, self.width, self.height - self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     # background
     painter.save()
     if self.headerAtBottom:
         h = self.height
     else:
         h = self.height - self.headerHeight
     painter.translate(0, h)
     painter.scale(1, -1)
     self.drawCellBackground(painter, bodyRect)
     painter.restore()
     # glyph
     if self.headerAtBottom:
         painter.translate(0, self.headerHeight)
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(painter, bodyRect)
         self.drawCellVerticalMetrics(painter, bodyRect)
     painter.save()
     painter.setClipRect(0, 0, self.width, self.height - self.headerHeight)
     painter.translate(self.xOffset, self.yOffset)
     painter.scale(self.scale, self.scale)
     self.drawCellGlyph(painter)
     painter.restore()
     # foreground
     painter.save()
     painter.translate(0, self.height - self.headerHeight)
     painter.scale(1, -1)
     self.drawCellForeground(painter, bodyRect)
     painter.restore()
     # header
     if self.shouldDrawHeader:
         painter.save()
         if self.headerAtBottom:
             h = 0
         else:
             h = self.height
         painter.translate(0, h)
         painter.scale(1, -1)
         self.drawCellHeaderBackground(painter, headerRect)
         self.drawCellHeaderText(painter, headerRect)
         painter.restore()
     return pixmap
Exemplo n.º 15
0
 def paintEvent(self, paint_event):
     painter = QPainter(self)
     if self._page_number == 0:
         painter.setClipRect(QRectF(0, 0, self.page.width(), self.page.height()-self._offset_top()))
         painter.translate(0, -self._offset_top())
     else:
         painter.setClipRect(QRectF(0, 0, self.page.width(), self.page.height()))
         height = self.page.height()
         painter.translate(0, -self._page_number*height)
     self._document.drawContents(painter)
Exemplo n.º 16
0
 def getPixmap(self):
     pixmap = QPixmap(self.width * self.pixelRatio, self.height * self.pixelRatio)
     pixmap.setDevicePixelRatio(self.pixelRatio)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, self.height)
     painter.scale(1, -1)
     if self.headerAtBottom:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     else:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     # background
     painter.save()
     if self.headerAtBottom:
         h = self.height
     else:
         h = self.height - self.headerHeight
     painter.translate(0, h)
     painter.scale(1, -1)
     self.drawCellBackground(painter, bodyRect)
     painter.restore()
     # glyph
     if self.headerAtBottom:
         painter.translate(0, self.headerHeight)
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(painter, bodyRect)
         self.drawCellVerticalMetrics(painter, bodyRect)
     painter.save()
     painter.setClipRect(0, 0, self.width, self.height-self.headerHeight)
     painter.translate(self.xOffset, self.yOffset)
     painter.scale(self.scale, self.scale)
     self.drawCellGlyph(painter)
     painter.restore()
     # foreground
     painter.save()
     painter.translate(0, self.height - self.headerHeight)
     painter.scale(1, -1)
     self.drawCellForeground(painter, bodyRect)
     painter.restore()
     # header
     if self.shouldDrawHeader:
         painter.save()
         if self.headerAtBottom:
             h = 0
         else:
             h = self.height
         painter.translate(0, h)
         painter.scale(1, -1)
         self.drawCellHeaderBackground(painter, headerRect)
         self.drawCellHeaderText(painter, headerRect)
         painter.restore()
     return pixmap
Exemplo n.º 17
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setClipRect(0, 0, self.width(), self.height())

        if self.object is None:
            return

        self.object.draw(painter, self.width(), self.height())

        painter.end()
Exemplo n.º 18
0
 def paintEvent(self, event):
     """
     Paint the interpolated pixmap image.
     """
     p = QPainter(self)
     p.setClipRect(event.rect())
     factor = self.blendingFactor_**2
     if self.pixmap1 and 1. - factor:
         p.setOpacity(1. - factor)
         p.drawPixmap(QPoint(0, 0), self.pixmap1)
     if self.pixmap2 and factor:
         p.setOpacity(factor)
         p.drawPixmap(QPoint(0, 0), self.pixmap2)
Exemplo n.º 19
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(event.rect(), Qt.white)
        painter.setFont(self.displayFont)

        redrawRect = event.rect()
        beginRow = redrawRect.top() // self.squareSize
        endRow = redrawRect.bottom() // self.squareSize
        beginColumn = redrawRect.left() // self.squareSize
        endColumn = redrawRect.right() // self.squareSize

        painter.setPen(Qt.gray)
        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):
                painter.drawRect(
                    column * self.squareSize,
                    row * self.squareSize,
                    self.squareSize,
                    self.squareSize,
                )

        fontMetrics = QFontMetrics(self.displayFont)
        painter.setPen(Qt.black)
        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):
                key = row * self.columns + column
                painter.setClipRect(
                    column * self.squareSize,
                    row * self.squareSize,
                    self.squareSize,
                    self.squareSize,
                )

                if key == self.lastKey:
                    painter.fillRect(
                        column * self.squareSize + 1,
                        row * self.squareSize + 1,
                        self.squareSize,
                        self.squareSize,
                        Qt.red,
                    )

                key_ch = self._chr(key)
                painter.drawText(
                    column * self.squareSize + (self.squareSize / 2) -
                    fontMetrics.width(key_ch) / 2,
                    row * self.squareSize + 4 + fontMetrics.ascent(),
                    key_ch,
                )
Exemplo n.º 20
0
    def paintEvent(self, event: QPaintEvent) -> None:
        sz = self.size()
        pen_width = int(self.pen_size / self.scaleFactor)
        self.pen.setWidth(pen_width)
        """ draw backgroud """
        static_image = QPixmap(sz)
        bpainter = QPainter()
        bpainter.begin(static_image)
        o = 10
        bg = self.palette().brush(QPalette.Window)
        bpainter.fillRect(0, 0, o, o, bg)
        bpainter.fillRect(self.width() - o, 0, o, o, bg)
        bpainter.fillRect(0, self.height() - o, o, o, bg)
        bpainter.fillRect(self.width() - o, self.height() - o, o, o, bg)
        bpainter.setClipRect(self.rect())
        bpainter.setRenderHint(QPainter.Antialiasing)
        bpainter.drawTiledPixmap(self.rect(), self.m_tile)
        bpainter.end()
        bpainter.begin(self)
        bpainter.drawPixmap(self.rect(), static_image)

        if self.state == self.State.disable:
            painter = QPainter()
            painter.begin(self)
            painter.drawPixmap(0, 0, sz.width(), sz.height(), self.currn_pix)
            painter.drawPixmap(0, 0, sz.width(), sz.height(), self.trans_pix)
            painter.end()
        else:
            painter = QPainter()
            painter.begin(self.trans_pix)
            if self.drawmode == self.DrawMode.line:
                painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
            elif self.drawmode == self.DrawMode.clear:
                painter.setCompositionMode(QPainter.CompositionMode_Clear)
            painter.setPen(self.pen)
            self.drawingPath.drawPath(painter)
            painter.end()
            painter2 = QPainter()
            painter2.begin(self)
            painter2.drawPixmap(0, 0, sz.width(), sz.height(), self.currn_pix)
            painter2.drawPixmap(0, 0, sz.width(), sz.height(), self.trans_pix)
            if self.mousePressed:
                painter2.setPen(QPen(Qt.SolidLine))
                painter2.setBrush(
                    QBrush(QColor(255, 255, 255, 0), Qt.SolidPattern))
                painter2.setRenderHint(QPainter.Antialiasing, True)
                painter2.drawEllipse(self.cur_point, self.pen_size // 2,
                                     self.pen_size // 2)
            painter2.end()
Exemplo n.º 21
0
 def _paint(self, painter: QtGui.QPainter,
            paint_rect: QtCore.QRect) -> None:
     p = QtCore.QPoint(self.leftMargin(), 0)
     for measure_editor in self.measure_editors():
         measure_rect = QtCore.QRect(p.x(), 0, measure_editor.width(),
                                     self.height())
         measure_rect = measure_rect.intersected(paint_rect)
         if not measure_rect.isEmpty():
             painter.save()
             try:
                 painter.setClipRect(measure_rect)
                 painter.translate(p)
                 measure_editor.paint(painter, measure_rect.translated(-p))
             finally:
                 painter.restore()
         p += QtCore.QPoint(measure_editor.width(), 0)
Exemplo n.º 22
0
    def paint(self, painter: QPainter, option, index):
        # reference following link
        # https://stackoverflow.com/questions/53353450/how-to-highlight-a-words-in-qtablewidget-from-a-searchlist
        # https://stackoverflow.com/questions/34623036/implementing-a-delegate-for-wordwrap-in-a-qtreeview-qt-pyside-pyqt
        painter.save()
        doc = QTextDocument(self)
        # option.palette.setColor(QPalette.HighlightedText, QColor.fromRgb(30, 136, 200))
        # remove dotted border in table
        if option.state & QStyle.State_HasFocus:
            option.state = option.state ^ QStyle.State_HasFocus
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)
        doc.setPlainText(options.text)
        # keyword = index.data(Qt.UserRole)
        # if self.keywords:
        self.keywordHighlight(doc)
        options.text = ""
        # print(dir(options.palette))

        # print(options.palette.Highlight)
        style = QApplication.style() if options.widget is None \
            else options.widget.style()
        style.drawControl(QStyle.CE_ItemViewItem, options, painter,
                          options.widget)  # for selection highlight

        ctx = QAbstractTextDocumentLayout.PaintContext()

        if index.data(Qt.UserRole) == 'reserved':
            ctx.palette.setColor(QPalette.Text, QColor.fromRgb(100, 100, 100))
            doc.setDefaultFont(
                QFont(option.font.family(),
                      option.font.pointSize() * 2 // 3))

        else:
            ctx.palette.setColor(QPalette.Text, QColor.fromRgb(217, 217, 217))
            doc.setDefaultFont(option.font)

        textRect = option.rect
        # margin = 4
        # textRect.setTop(textRect.top() + margin)
        textRect.setTop(textRect.top())
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))

        doc.setTextWidth(option.rect.width())
        doc.documentLayout().draw(painter, ctx)
        painter.restore()
Exemplo n.º 23
0
    def _paint(self, painter: QtGui.QPainter,
               paint_rect: QtCore.QRect) -> None:
        self.renderTimeGrid(painter, paint_rect)

        for item in self.__samples:
            sample_rect = item.rect().intersected(paint_rect)
            if not sample_rect.isEmpty():
                painter.save()
                try:
                    painter.setClipRect(sample_rect)
                    painter.translate(item.pos())
                    item.paint(painter, sample_rect.translated(-item.pos()))
                finally:
                    painter.restore()

        if self.__playback_time is not None:
            pos = self.timeToX(self.__playback_time)
            painter.fillRect(pos, 0, 2, self.height(), QtGui.QColor(0, 0, 160))
Exemplo n.º 24
0
    def drawForeground(self, painter: QPainter, rect):
        if self.guidesEnabled:
            rect = self.chart().plotArea()

            text = []
            for serie in self.chart().series():
                pointer_coords = self.chart().mapToValue(self.coords, serie)
                x_y_points = list(
                    zip(*((e.x(), e.y()) for e in serie.pointsVector())))
                point_ind = bisect.bisect_left(x_y_points[0],
                                               pointer_coords.x())
                point = serie.at(point_ind - 1 if point_ind else 0)
                text.append("%f x %f" % (point.x(), point.y()))
            painter.drawText(70, 27, ', '.join(text))
            painter.setClipRect(rect)
            # painter.setPen(self.guidePen)
            painter.drawLine(self.coords.x(), rect.top(), self.coords.x(),
                             rect.bottom())
Exemplo n.º 25
0
    def paintEvent(self, event):

        painter = QPainter()
        painter.begin(self)
        painter.fillRect(event.rect(), QBrush(Qt.white))
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(QBrush(Qt.red), 1, Qt.DashLine))
        painter.drawRect(self.largest_rect)
        painter.setPen(QPen(Qt.black))
        painter.drawRect(self.clip_rect)
        for i in range(4):
            painter.drawRect(self.corner(i))

        painter.setClipRect(self.clip_rect)
        painter.drawPolyline(self.polygon)
        painter.setBrush(QBrush(Qt.blue))
        painter.drawPath(self.path)
        painter.end()
Exemplo n.º 26
0
    def paintEvent(self, ev):
        rect = ev.rect()
        s = self._square
        rows = range(rect.top() // s, rect.bottom() // s + 1)
        cols = range(rect.left() // s, rect.right() // s + 1)

        painter = QPainter(self)
        painter.setPen(QPen(self.palette().color(QPalette.Window)))
        painter.setFont(self._font)
        metrics = QFontMetrics(self._font)

        # draw characters on white tiles
        tile = self.palette().color(QPalette.Base)
        selected_tile = self.palette().color(QPalette.Highlight)
        selected_tile.setAlpha(96)
        selected_box = self.palette().color(QPalette.Highlight)

        text_pen = QPen(self.palette().text().color())
        disabled_pen = QPen(self.palette().color(QPalette.Disabled,
                                                 QPalette.Text))
        selection_pen = QPen(selected_box)
        for row in rows:
            for col in cols:
                char = row * self._column_count + col + self._range[0]
                if char > self._range[1]:
                    break
                printable = self.isprint(char)
                painter.setClipRect(col * s, row * s, s, s)
                if char == self._selected:
                    painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2,
                                     selected_tile)
                    painter.setPen(selection_pen)
                    painter.drawRect(col * s, row * s, s - 1, s - 1)
                elif printable:
                    painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2,
                                     tile)
                painter.setPen(text_pen if printable else disabled_pen)
                t = chr(char)
                x = col * s + s // 2 - metrics.width(t) // 2
                y = row * s + 4 + metrics.ascent()
                painter.drawText(x, y, t)
            else:
                continue
            break
Exemplo n.º 27
0
 def paintEvent(self, ev):
     rect = ev.rect()
     s = self._square
     rows = range(rect.top() // s, rect.bottom() // s + 1)
     cols = range(rect.left() // s, rect.right() // s + 1)
     
     painter = QPainter(self)
     painter.setPen(QPen(self.palette().color(QPalette.Window)))
     painter.setFont(self._font)
     metrics = QFontMetrics(self._font)
     
     # draw characters on white tiles
     tile = self.palette().color(QPalette.Base)
     selected_tile = self.palette().color(QPalette.Highlight)
     selected_tile.setAlpha(96)
     selected_box = self.palette().color(QPalette.Highlight)
     
     text_pen = QPen(self.palette().text().color())
     disabled_pen = QPen(self.palette().color(QPalette.Disabled, QPalette.Text))
     selection_pen = QPen(selected_box)
     for row in rows:
         for col in cols:
             char = row * self._column_count + col + self._range[0]
             if char > self._range[1]:
                 break
             printable = self.isprint(char)
             painter.setClipRect(col * s, row * s, s, s)
             if char == self._selected:
                 painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, selected_tile)
                 painter.setPen(selection_pen)
                 painter.drawRect(col * s, row * s, s - 1, s - 1)
             elif printable:
                 painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, tile)
             painter.setPen(text_pen if printable else disabled_pen)
             t = chr(char)
             x = col * s + s // 2 - metrics.width(t) // 2
             y = row * s + 4 + metrics.ascent()
             painter.drawText(x, y, t)
         else:
             continue
         break
Exemplo n.º 28
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(event.rect(), Qt.white)
        painter.setFont(self.displayFont)

        redrawRect = event.rect()
        beginRow = redrawRect.top() // self.cellSize
        endRow = redrawRect.bottom() // self.cellSize
        beginColumn = redrawRect.left() // self.cellSize
        endColumn = redrawRect.right() // self.cellSize

        # grid
        painter.setPen(Qt.gray)
        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):
                painter.drawRect(column * self.cellSize,
                        row * self.cellSize, self.cellSize,
                        self.cellSize)


        fontMetrics = QFontMetrics(self.displayFont)
        painter.setPen(Qt.black)

        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):

                key = row * self.columns + column
                painter.setClipRect(column * self.cellSize,
                        row * self.cellSize, self.cellSize,
                        self.cellSize)

                if key == self.lastKey:
                    painter.fillRect(column * self.cellSize + 1,
                            row * self.cellSize + 1, self.cellSize,
                            self.cellSize, Qt.red)

                key_ch = self._chr(key)
                painter.drawText(column * self.cellSize + (self.cellSize / 2) - fontMetrics.width(key_ch) / 2,
                        row * self.cellSize + 4 + fontMetrics.ascent(),
                        key_ch)
Exemplo n.º 29
0
    def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None:
        super().paint(painter, option, index)
        polygon_id = index.data(BaseColorMappingDialog.PolygonRole)
        brushstyle = index.data(BaseColorMappingDialog.BrushStyleRole)
        h = option.rect.height()

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setClipRect(option.rect)
        painter.setPen(QPen(Qt.lightGray, h/5.))
        if brushstyle is not None:
            painter.setBrush(QBrush(Qt.lightGray, brushstyle))
        zoom = .9
        painter.setTransform(QTransform()
                             .translate(option.rect.x()+h/2+10, option.rect.y()+h/2)
                             .rotate(-5.)
                             .scale(h/100.*zoom, h/100.*zoom))
        if polygon_id is None or polygon_id == NodePolygon.Circle:
            painter.drawEllipse(QRect(-50, -50, 100, 100))
        else:
            polygon = NODE_POLYGON_MAP.get(polygon_id, QPolygonF())
            painter.drawPolygon(polygon)
        painter.restore()
Exemplo n.º 30
0
    def paintEvent(self, event):
        painter = QPainter(self)
        metrics = self.fontMetrics()

        # tabs
        self._closeRects = {}
        self._tabsRects = {}
        painter.save()
        currentTab = self.currentTab()
        tabFillColor = QColor(240, 240, 240)
        hoverFillColor = QColor(253, 253, 255)
        textHeight = metrics.lineSpacing()
        left = 0
        h = textHeight + topPadding * 2
        for index, name in enumerate(self.tabs()):
            isHeroFirstTab = not index and self._heroFirstTab
            isClosable = not isHeroFirstTab
            textWidth = self._textWidth
            if not index:
                textWidth += self._firstOffset
            w = sidePadding * 2 + textWidth
            if isClosable:
                w += crossMargin + crossSize
            self._tabsRects[index] = (left, 0, w, h)

            # background
            textColor = QColor(72, 72, 72)
            if index == currentTab:
                fillColor = tabFillColor
            elif index == self._hoverTab:
                fillColor = hoverFillColor
            else:
                fillColor = None
            if fillColor is not None:
                painter.fillRect(0, 0, w, h, fillColor)
            # text
            painter.save()
            painter.translate(sidePadding, metrics.ascent() + topPadding)
            painter.setPen(textColor)
            painter.setRenderHint(QPainter.Antialiasing)
            painter.drawText(
                0, 0, metrics.elidedText(name, Qt.ElideRight, textWidth))
            # cross
            if isClosable:
                # 3px padding for click rect
                self._closeRects[index] = (left + textWidth + 2 * sidePadding -
                                           3, metrics.ascent() + topPadding -
                                           crossSize - 3, crossSize + 6,
                                           crossSize + 6)
                if index == self._hoverClose:
                    color = QColor(254, 28, 28)
                else:
                    color = QColor(78, 78, 78)
                painter.setPen(color)
                pen = painter.pen()
                pen.setWidthF(1.5)
                painter.setPen(pen)
                painter.translate(textWidth + sidePadding, -crossSize)
                painter.setClipRect(0, 0, crossSize, crossSize)
                painter.scale(crossSize / 10, crossSize / 10)
                painter.drawPath(cross)
            painter.restore()
            # shift for the next tab
            shift = textWidth + 2 * sidePadding + spacing
            if isClosable:
                shift += crossMargin + crossSize
            painter.translate(shift, 0)
            left += shift
        painter.restore()
Exemplo n.º 31
0
    def paintEvent(self, evt):
        """
        Protected method handling paint events.
        
        @param evt paint event (QPaintEvent)
        """
        if self.__grabbing:  # grabWindow() should just get the background
            return

        painter = QPainter(self)
        pal = QPalette(QToolTip.palette())
        font = QToolTip.font()

        handleColor = pal.color(QPalette.Active, QPalette.Highlight)
        handleColor.setAlpha(160)
        overlayColor = QColor(0, 0, 0, 160)
        textColor = pal.color(QPalette.Active, QPalette.Text)
        textBackgroundColor = pal.color(QPalette.Active, QPalette.Base)
        painter.drawPixmap(0, 0, self.__pixmap)
        painter.setFont(font)

        r = QRect(self.__selection)
        if not self.__selection.isNull():
            grey = QRegion(self.rect())
            if self.__mode == SnapshotRegionGrabber.Ellipse:
                reg = QRegion(r, QRegion.Ellipse)
            else:
                reg = QRegion(r)
            grey = grey.subtracted(reg)
            painter.setClipRegion(grey)
            painter.setPen(Qt.NoPen)
            painter.setBrush(overlayColor)
            painter.drawRect(self.rect())
            painter.setClipRect(self.rect())
            drawRect(painter, r, handleColor)

        if self.__showHelp:
            painter.setPen(textColor)
            painter.setBrush(textBackgroundColor)
            self.__helpTextRect = painter.boundingRect(
                self.rect().adjusted(2, 2, -2, -2), Qt.TextWordWrap,
                self.__helpText).translated(-self.__desktop.x(),
                                            -self.__desktop.y())
            self.__helpTextRect.adjust(-2, -2, 4, 2)
            drawRect(painter, self.__helpTextRect, textColor,
                     textBackgroundColor)
            painter.drawText(self.__helpTextRect.adjusted(3, 3, -3, -3),
                             Qt.TextWordWrap, self.__helpText)

        if self.__selection.isNull():
            return

        # The grabbed region is everything which is covered by the drawn
        # rectangles (border included). This means that there is no 0px
        # selection, since a 0px wide rectangle will always be drawn as a line.
        txt = "{0}, {1} ({2} x {3})".format(
            self.__locale.toString(self.__selection.x()),
            self.__locale.toString(self.__selection.y()),
            self.__locale.toString(self.__selection.width()),
            self.__locale.toString(self.__selection.height()))
        textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt)
        boundingRect = textRect.adjusted(-4, 0, 0, 0)

        if textRect.width() < r.width() - 2 * self.__handleSize and \
           textRect.height() < r.height() - 2 * self.__handleSize and \
           r.width() > 100 and \
           r.height() > 100:
            # center, unsuitable for small selections
            boundingRect.moveCenter(r.center())
            textRect.moveCenter(r.center())
        elif r.y() - 3 > textRect.height() and \
                r.x() + textRect.width() < self.rect().width():
            # on top, left aligned
            boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3))
            textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3))
        elif r.x() - 3 > textRect.width():
            # left, top aligned
            boundingRect.moveTopRight(QPoint(r.x() - 3, r.y()))
            textRect.moveTopRight(QPoint(r.x() - 5, r.y()))
        elif r.bottom() + 3 + textRect.height() < self.rect().bottom() and \
                r.right() > textRect.width():
            # at bottom, right aligned
            boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3))
            textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3))
        elif r.right() + textRect.width() + 3 < self.rect().width():
            # right, bottom aligned
            boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom()))
            textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom()))

        # If the above didn't catch it, you are running on a very
        # tiny screen...
        drawRect(painter, boundingRect, textColor, textBackgroundColor)
        painter.drawText(textRect, Qt.AlignHCenter, txt)

        if (r.height() > self.__handleSize * 2 and
            r.width() > self.__handleSize * 2) or \
           not self.__mouseDown:
            self.__updateHandles()
            painter.setPen(Qt.NoPen)
            painter.setBrush(handleColor)
            painter.setClipRegion(
                self.__handleMask(SnapshotRegionGrabber.StrokeMask))
            painter.drawRect(self.rect())
            handleColor.setAlpha(60)
            painter.setBrush(handleColor)
            painter.setClipRegion(
                self.__handleMask(SnapshotRegionGrabber.FillMask))
            painter.drawRect(self.rect())
Exemplo n.º 32
0
    def paintEvent(self, event):
        # init
        menustyle = kikka.core.getGhost(self.gid).getMenuStyle()
        self._bg_image = menustyle.bg_image
        self._fg_image = menustyle.fg_image
        self._side_image = menustyle.side_image
        self.updateActionRect()
        p = QPainter(self)

        # draw background
        p.fillRect(QRect(QPoint(), self.size()), self._side_image.pixelColor(0, 0))
        vertical = False
        y = self.height()
        while y > 0:
            yy = y - self._bg_image.height()
            p.drawImage(0, yy, self._side_image.mirrored(False, vertical))
            x = self._side_image.width()
            while x < self.width():
                p.drawImage(x, yy, self._bg_image.mirrored(False, vertical))
                x += self._bg_image.width()
                p.drawImage(x, yy, self._bg_image.mirrored(True, vertical))
                x += self._bg_image.width() + 1
            y -= self._bg_image.height()
            vertical = not vertical

        # draw item
        actioncount = len(self.actions())
        for i in range(actioncount):
            act = self.actions()[i]
            arect = QRect(self._aRect[i])
            if event.rect().intersects(arect) is False:
                continue

            opt = QStyleOptionMenuItem()
            self.initStyleOption(opt, act)
            opt.rect = arect
            if opt.state & QStyle.State_Selected \
                    and opt.state & QStyle.State_Enabled:
                # Selected Item, draw foreground image
                p.setClipping(True)
                p.setClipRect(arect.x() + self._side_image.width(), arect.y(), self.width() - self._side_image.width(),
                              arect.height())

                p.fillRect(QRect(QPoint(), self.size()), self._fg_image.pixelColor(0, 0))
                vertical = False
                y = self.height()
                while y > 0:
                    x = self._side_image.width()
                    while x < self.width():
                        yy = y - self._fg_image.height()
                        p.drawImage(x, yy, self._fg_image.mirrored(False, vertical))
                        x += self._fg_image.width()
                        p.drawImage(x, yy, self._fg_image.mirrored(True, vertical))
                        x += self._fg_image.width() + 1
                    y -= self._fg_image.height()
                    vertical = not vertical
                p.setClipping(False)

            if opt.menuItemType == QStyleOptionMenuItem.Separator:
                # Separator
                p.setPen(menustyle.getPenColor(opt))
                y = int(arect.y() + arect.height() / 2)
                p.drawLine(self._side_image.width(), y, arect.width(), y)
            else:
                # MenuItem
                self.drawControl(p, opt, arect, act.icon(), menustyle)
        pass  # exit for
Exemplo n.º 33
0
    def drawWaveforms(self):
        painter = QPainter(self.pixmap)
        length = Rhd2000DataBlock.getSamplesPerDataBlock(
        ) * self.numUsbBlocksToPlot

        polyline = [0] * (length + 1)

        # Assume all frames are the same size.
        yAxisLength = (self.frameList[self.numFramesIndex[self.selectedPort]]
                       [0].height() - 2) / 2.0
        tAxisLength = self.frameList[self.numFramesIndex[
            self.selectedPort]][0].width() - 1

        for j in range(
                len(self.frameList[self.numFramesIndex[self.selectedPort]])):
            stream = self.selectedChannelIndex(
                j + self.topLeftFrame[self.selectedPort]).boardStream
            channel = self.selectedChannelIndex(
                j + self.topLeftFrame[self.selectedPort]).chipChannel
            stype = self.selectedChannelIndex(
                j + self.topLeftFrame[self.selectedPort]).signalType

            if self.selectedChannelIndex(
                    j + self.topLeftFrame[self.selectedPort]).enabled:
                xOffset = self.frameList[self.numFramesIndex[
                    self.selectedPort]][j].left() + 1
                xOffset += self.tPosition * tAxisLength / self.tScale

                # Set clipping region
                adjustedFrame = copy(
                    self.frameList[self.numFramesIndex[self.selectedPort]][j])
                adjustedFrame.adjust(0, 1, 0, 0)
                painter.setClipRect(adjustedFrame)

                # Erase segment of old wavefrom
                eraseBlock = copy(adjustedFrame)
                eraseBlock.setLeft(xOffset)
                eraseBlock.setRight(
                    (tAxisLength * (1000.0 / self.sampleRate) / self.tScale) *
                    (length - 1) + xOffset)
                painter.eraseRect(eraseBlock)

                # Redraw y = 0 axis
                self.drawAxisLines(painter, j)

                if stype == constants.AmplifierSignal:
                    # Plot RHD2000 amplifier waveform

                    tStepMsec = 1000.0 / self.sampleRate
                    xScaleFactor = tAxisLength * tStepMsec / self.tScale
                    yScaleFactor = -yAxisLength / self.yScale
                    yOffset = self.frameList[self.numFramesIndex[
                        self.selectedPort]][j].center().y()

                    # build waveform
                    for i in range(length):
                        polyline[i + 1] = QPointF(
                            xScaleFactor * i + xOffset,
                            yScaleFactor * self.signalProcessor.
                            amplifierPostFilter[stream][channel][i] + yOffset)

                    # join to old waveform
                    if self.tPosition == 0.0:
                        polyline[0] = polyline[1]
                    else:
                        polyline[0] = QPointF(
                            xScaleFactor * -1 + xOffset,
                            yScaleFactor * self.plotDataOld[
                                j + self.topLeftFrame[self.selectedPort]] +
                            yOffset)

                    # save last point in waveform to join to next segment
                    self.plotDataOld[j + self.topLeftFrame[
                        self.
                        selectedPort]] = self.signalProcessor.amplifierPostFilter[
                            stream][channel][length - 1]

                    # draw waveform
                    painter.setPen(Qt.blue)
                    if self.pointPlotMode:
                        painter.drawPoints(QPolygonF(polyline))
                    else:
                        painter.drawPolyline(QPolygonF(polyline))

                elif stype == constants.AuxInputSignal:
                    # Plot RHD2000 auxiliary input signal

                    tStepMsec = 1000.0 / (self.sampleRate / 4)
                    xScaleFactor = tAxisLength * tStepMsec / self.tScale
                    yScaleFactor = -(2.0 * yAxisLength) / 2.5
                    yOffset = self.frameList[self.numFramesIndex[
                        self.selectedPort]][j].bottom()

                    # build waveform
                    for i in range(length / 4):
                        polyline[i + 1] = QPointF(
                            xScaleFactor * i + xOffset, yScaleFactor *
                            self.signalProcessor.auxChannel[stream][channel][i]
                            + yOffset)

                    # join to old waveform
                    if self.tPosition == 0.0:
                        polyline[0] = polyline[1]
                    else:
                        polyline[0] = QPointF(
                            xScaleFactor * -1 + xOffset,
                            yScaleFactor * self.plotDataOld[
                                j + self.topLeftFrame[self.selectedPort]] +
                            yOffset)

                    # save last point in waveform to join to next segment
                    self.plotDataOld[j + self.topLeftFrame[
                        self.selectedPort]] = self.signalProcessor.auxChannel[
                            stream][channel][(length / 4) - 1]

                    # draw waveform
                    pen = QPen()
                    pen.setColor(QColor(200, 50, 50))
                    painter.setPen(pen)
                    polyline = polyline[:(length // 4) + 1]
                    if self.pointPlotMode:
                        painter.drawPoints(QPolygonF(polyline))
                    else:
                        painter.drawPolyline(QPolygonF(polyline))

                elif stype == constants.SupplyVoltageSignal:
                    # Plot RHD2000 supply voltage signal

                    tStepMsec = 1000.0 / (self.sampleRate / 60.0)
                    xScaleFactor = tAxisLength * tStepMsec / self.tScale
                    yScaleFactor = -(2.0 * yAxisLength) / 1.5
                    yOffset = self.frameList[self.numFramesIndex[
                        self.selectedPort]][j].bottom()

                    voltageLow = False
                    voltageOutOfRange = False

                    # build waveform
                    for i in range(length / 60):
                        voltage = self.signalProcessor.supplyVoltage[stream][i]
                        polyline[i + 1] = QPointF(
                            xScaleFactor * i + xOffset,
                            yScaleFactor * (voltage - 2.5) + yOffset)
                        if voltage < 2.9 or voltage > 3.6:
                            voltageOutOfRange = True
                        elif voltage < 3.2:
                            voltageLow = True

                    # join to old waveform
                    if self.tPosition == 0.0:
                        polyline[0] = polyline[1]
                    else:
                        polyline[0] = QPointF(
                            xScaleFactor * -1 + xOffset,
                            yScaleFactor *
                            (self.plotDataOld[j + self.topLeftFrame[
                                self.selectedPort]] - 2.5) + yOffset)

                    # save last point in waveform to join to next segment
                    self.plotDataOld[j + self.topLeftFrame[
                        self.
                        selectedPort]] = self.signalProcessor.supplyVoltage[
                            stream][(length / 60) - 1]

                    # draw waveform
                    painter.setPen(Qt.green)
                    if voltageLow:
                        painter.setPen(Qt.yellow)
                    if voltageOutOfRange:
                        painter.setPen(Qt.red)

                    polyline = polyline[:(length // 60) + 1]
                    if self.pointPlotMode:
                        painter.drawPoints(QPolygonF(polyline))
                    else:
                        painter.drawPolyline(QPolygonF(polyline))

                elif stype == constants.BoardAdcSignal:
                    # Plot USB interface board ADC input signal

                    tStepMsec = 1000.0 / self.sampleRate
                    xScaleFactor = tAxisLength * tStepMsec / self.tScale
                    yScaleFactor = -(2.0 * yAxisLength) / 3.3
                    yOffset = self.frameList[self.numFramesIndex[
                        self.selectedPort]][j].bottom()

                    # build waveform
                    for i in range(length):
                        polyline[i + 1] = QPointF(
                            xScaleFactor * i + xOffset, yScaleFactor *
                            self.signalProcessor.boardAdc[channel][i] +
                            yOffset)

                    # join to old waveform
                    if self.tPosition == 0.0:
                        polyline[0] = polyline[1]
                    else:
                        polyline[0] = QPointF(
                            xScaleFactor * -1 + xOffset,
                            yScaleFactor * self.plotDataOld[
                                j + self.topLeftFrame[self.selectedPort]] +
                            yOffset)

                    # save last point in waveform to join to next segment
                    self.plotDataOld[j + self.topLeftFrame[
                        self.selectedPort]] = self.signalProcessor.boardAdc[
                            channel][length - 1]

                    # draw waveform
                    painter.setPen(Qt.darkGreen)
                    if self.pointPlotMode:
                        painter.drawPoints(QPolygonF(polyline))
                    else:
                        painter.drawPolyline(QPolygonF(polyline))

                elif stype == constants.BoardDigInSignal:
                    # Plot USB interface board digital input signal

                    tStepMsec = 1000.0 / self.sampleRate
                    xScaleFactor = tAxisLength * tStepMsec / self.tScale
                    yScaleFactor = -(2.0 * yAxisLength) / 2.0
                    yOffset = (self.frameList[self.numFramesIndex[
                        self.selectedPort]][j].bottom() +
                               self.frameList[self.numFramesIndex[
                                   self.selectedPort]][j].center().y()) / 2.0

                    # build waveform
                    for i in range(length):
                        polyline[i + 1] = QPointF(
                            xScaleFactor * i + xOffset, yScaleFactor *
                            self.signalProcessor.boardDigIn[channel][i] +
                            yOffset)

                    # join to old waveform
                    if self.tPosition == 0.0:
                        polyline[0] = polyline[1]
                    else:
                        polyline[0] = QPointF(
                            xScaleFactor * -1 + xOffset,
                            yScaleFactor * self.plotDataOld[
                                j + self.topLeftFrame[self.selectedPort]] +
                            yOffset)

                    # save last point in waveform to join to next segment
                    self.plotDataOld[j + self.topLeftFrame[
                        self.selectedPort]] = self.signalProcessor.boardDigIn[
                            channel][length - 1]

                    # draw waveform
                    pen = QPen()
                    pen.setColor(QColor(200, 50, 200))
                    painter.setPen(pen)
                    if self.pointPlotMode:
                        painter.drawPoints(QPolygonF(polyline))
                    else:
                        painter.drawPolyline(QPolygonF(polyline))
                painter.setClipping(False)

        tStepMsec = 1000.0 / self.sampleRate
        self.tPosition += length * tStepMsec
        if self.tPosition >= self.tScale:
            self.tPosition = 0.0
Exemplo n.º 34
0
 def paintEvent(self, evt):
     """
     Protected method handling paint events.
     
     @param evt paint event (QPaintEvent)
     """
     if self.__grabbing:     # grabWindow() should just get the background
         return
     
     painter = QPainter(self)
     pal = QPalette(QToolTip.palette())
     font = QToolTip.font()
     
     handleColor = pal.color(QPalette.Active, QPalette.Highlight)
     handleColor.setAlpha(160)
     overlayColor = QColor(0, 0, 0, 160)
     textColor = pal.color(QPalette.Active, QPalette.Text)
     textBackgroundColor = pal.color(QPalette.Active, QPalette.Base)
     painter.drawPixmap(0, 0, self.__pixmap)
     painter.setFont(font)
     
     r = QRect(self.__selection)
     if not self.__selection.isNull():
         grey = QRegion(self.rect())
         if self.__mode == SnapshotRegionGrabber.Ellipse:
             reg = QRegion(r, QRegion.Ellipse)
         else:
             reg = QRegion(r)
         grey = grey.subtracted(reg)
         painter.setClipRegion(grey)
         painter.setPen(Qt.NoPen)
         painter.setBrush(overlayColor)
         painter.drawRect(self.rect())
         painter.setClipRect(self.rect())
         drawRect(painter, r, handleColor)
     
     if self.__showHelp:
         painter.setPen(textColor)
         painter.setBrush(textBackgroundColor)
         self.__helpTextRect = painter.boundingRect(
             self.rect().adjusted(2, 2, -2, -2),
             Qt.TextWordWrap, self.__helpText).translated(
             -self.__desktop.x(), -self.__desktop.y())
         self.__helpTextRect.adjust(-2, -2, 4, 2)
         drawRect(painter, self.__helpTextRect, textColor,
                  textBackgroundColor)
         painter.drawText(
             self.__helpTextRect.adjusted(3, 3, -3, -3),
             Qt.TextWordWrap, self.__helpText)
     
     if self.__selection.isNull():
         return
     
     # The grabbed region is everything which is covered by the drawn
     # rectangles (border included). This means that there is no 0px
     # selection, since a 0px wide rectangle will always be drawn as a line.
     txt = "{0:n}, {1:n} ({2:n} x {3:n})".format(
         self.__selection.x(), self.__selection.y(),
         self.__selection.width(), self.__selection.height())
     textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt)
     boundingRect = textRect.adjusted(-4, 0, 0, 0)
     
     if textRect.width() < r.width() - 2 * self.__handleSize and \
        textRect.height() < r.height() - 2 * self.__handleSize and \
        r.width() > 100 and \
        r.height() > 100:
         # center, unsuitable for small selections
         boundingRect.moveCenter(r.center())
         textRect.moveCenter(r.center())
     elif r.y() - 3 > textRect.height() and \
             r.x() + textRect.width() < self.rect().width():
         # on top, left aligned
         boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3))
         textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3))
     elif r.x() - 3 > textRect.width():
         # left, top aligned
         boundingRect.moveTopRight(QPoint(r.x() - 3, r.y()))
         textRect.moveTopRight(QPoint(r.x() - 5, r.y()))
     elif r.bottom() + 3 + textRect.height() < self.rect().bottom() and \
             r.right() > textRect.width():
         # at bottom, right aligned
         boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3))
         textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3))
     elif r.right() + textRect.width() + 3 < self.rect().width():
         # right, bottom aligned
         boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom()))
         textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom()))
     
     # If the above didn't catch it, you are running on a very
     # tiny screen...
     drawRect(painter, boundingRect, textColor, textBackgroundColor)
     painter.drawText(textRect, Qt.AlignHCenter, txt)
     
     if (r.height() > self.__handleSize * 2 and
         r.width() > self.__handleSize * 2) or \
        not self.__mouseDown:
         self.__updateHandles()
         painter.setPen(Qt.NoPen)
         painter.setBrush(handleColor)
         painter.setClipRegion(
             self.__handleMask(SnapshotRegionGrabber.StrokeMask))
         painter.drawRect(self.rect())
         handleColor.setAlpha(60)
         painter.setBrush(handleColor)
         painter.setClipRegion(
             self.__handleMask(SnapshotRegionGrabber.FillMask))
         painter.drawRect(self.rect())
Exemplo n.º 35
0
	def paintMarkedRegions(self, evt):
		"""Draw the marked region indicators."""
		
		def f2px(frameNumber):
			"""Convert frame number to pixel coordinates."""
			return round(frameNumber / self.totalRecordedFrames * (self.uiMarkedRegionVisualization.width()-1))
		
		if not self.totalRecordedFrames:
			return
		
		p = QPainter(self.uiMarkedRegionVisualization)
		
		#This causes borders to get merged and generally mis-drawn.
		#Could otherwise be used to simplify math when calculating rect position.
		#p.setCompositionMode(QPainter.CompositionMode_DestinationOver)
		
		#This causes graphics glitches in 5.7 upon redraw.
		#Could otherwise be used to simplify math when calculating rect position.
		#p.scale(1,-1)
		#p.translate(0, -evt.rect().height()+1)
		
		#Draw the tracks of marked regions.
		trackOffset = -1
		for track in reversed(self._tracks):
			for region in track:
				regionRect = QRect(
					f2px(region['mark start']),
					trackOffset + self.saveRegionBorder,
					f2px(region['mark end'] - region['mark start']),
					self.saveRegionMarkerHeight,
				)
				
				if region['saved'] < 1: #Draw coloured, unsaved marked region.
					p.setPen(hsva(
						region['hue'],
						{-1:150, 0:230, 1:255}[region['highlight']],
						{-1:160, 0:190, 1:100}[region['highlight']],
					))
					p.setBrush(QBrush(hsva(
						region['hue'], 
						{-1:0, 0:153, 1:255}[region['highlight']], 
						{-1:0, 0:230, 1:255}[region['highlight']],
					)))
					p.setClipRect(regionRect.adjusted(regionRect.width() * region['saved'],0, 0,0))
					p.drawRect(regionRect)
				
				if region['saved'] > 0: #Draw green, saved marked region.
					p.setPen(hsva(
						120, #green
						{-1:150, 0:230, 1:255}[region['highlight']],
						{-1:160, 0:190, 1:100}[region['highlight']],
					))
					p.setBrush(QBrush(hsva(
						120, 
						{-1:0, 0:153, 1:255}[region['highlight']], 
						{-1:0, 0:230, 1:255}[region['highlight']],
					)))
					p.setClipRect(regionRect.adjusted(0,0, -regionRect.width() * (1-region['saved']),0))
					p.drawRect(regionRect)
			
			trackOffset += self.saveRegionMarkerOffset
Exemplo n.º 36
0
    def paintEvent(self, event):
        unused(event)
        compassAIIntrusion = 0
        compassHalfSpan = 180
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.HighQualityAntialiasing, True)

        tapeGaugeWidth = self.tapesGaugeWidthFor(self.width(), self.width())
        aiheight = self.height()
        aiwidth = self.width() - tapeGaugeWidth * 2
        if (aiheight > aiwidth):
            aiheight = aiwidth
        AIMainArea = QRectF(tapeGaugeWidth, 0, aiwidth, aiheight)
        AIPaintArea = QRectF(0, 0, self.width(), self.height())

        velocityMeterArea = QRectF(0, 0, tapeGaugeWidth, aiheight)
        altimeterArea = QRectF(AIMainArea.right(), 0, tapeGaugeWidth, aiheight)

        # calc starts
        compassRelativeWidth = 0.75
        compassBottomMargin = 0.78
        compassSize = compassRelativeWidth * AIMainArea.width(
        )  # Diameter is this times the width.
        compassCenterY = AIMainArea.bottom() + compassSize / 4

        if self.height(
        ) - compassCenterY > AIMainArea.width() / 2 * compassBottomMargin:
            compassCenterY = self.height(
            ) - AIMainArea.width() / 2 * compassBottomMargin
        compassCenterY = (compassCenterY * 2 + AIMainArea.bottom() +
                          compassSize / 4) / 3

        compassArea = QRectF(
            AIMainArea.x() +
            (1 - compassRelativeWidth) / 2 * AIMainArea.width(),
            compassCenterY - compassSize / 2, compassSize, compassSize)

        if self.height() - compassCenterY < compassSize / 2:
            compassHalfSpan = math.acos(
                (compassCenterY - self.height()) * 2 /
                compassSize) * 180 / math.pi + self.COMPASS_DISK_RESOLUTION
            if compassHalfSpan > 180:
                compassHalfSpan = 180

        compassAIIntrusion = compassSize / 2 + AIMainArea.bottom(
        ) - compassCenterY
        if compassAIIntrusion < 0:
            compassAIIntrusion = 0
        #calc ends

        hadClip = painter.hasClipping()

        painter.setClipping(True)
        painter.setClipRect(AIPaintArea)

        self.drawAIGlobalFeatures(painter, AIMainArea, AIPaintArea)
        self.drawAIAttitudeScales(painter, AIMainArea, compassAIIntrusion)
        self.drawAIAirframeFixedFeatures(painter, AIMainArea)
        self.drawAICompassDisk(painter, compassArea, compassHalfSpan)

        painter.setClipping(hadClip)
        if self.isGPSAltitudePrimary:
            self.drawAltimeter(painter, altimeterArea, self.GPSAltitude,
                               self.primaryAltitude, self.verticalVelocity)
        else:
            self.drawAltimeter(painter, altimeterArea, self.primaryAltitude,
                               self.GPSAltitude, self.verticalVelocity)
        if self.isGPSSpeedPrimary:
            self.drawVelocityMeter(painter, velocityMeterArea,
                                   self.groundspeed, self.primarySpeed)
        else:
            self.drawVelocityMeter(painter, velocityMeterArea,
                                   self.primarySpeed, self.groundspeed)
        painter.end()
Exemplo n.º 37
0
    def updateSpikePlot(self, rms):
        tScale = 3.0  # time scale = 3.0 ms

        colorIndex = 2
        if self.maxNumSpikeWaveforms == 10:
            colorIndex = 0
        elif self.maxNumSpikeWaveforms == 20:
            colorIndex = 1
        elif self.maxNumSpikeWaveforms == 30:
            colorIndex = 2

        self.drawAxisLines()

        if self.pixmap is None:
            painter = QPainter()
        else:
            painter = QPainter(self.pixmap)

        # Vector for waveform plot points
        polyline = [0] * self.totalTSteps

        yAxisLength = (self.frame.height() - 2) / 2.0
        tAxisLength = self.frame.width() - 1

        xOffset = self.frame.left() + 1

        # Set clipping region for plotting.
        adjustedFrame = copy(self.frame)
        adjustedFrame.adjust(0, 1, 0, 0)
        painter.setClipRect(adjustedFrame)

        xScaleFactor = tAxisLength * self.tStepMsec / tScale
        yScaleFactor = -yAxisLength / self.yScale
        yOffset = self.frame.center().y()

        index = self.maxNumSpikeWaveforms - self.numSpikeWaveforms
        for j in range(self.spikeWaveformIndex - self.numSpikeWaveforms,
                       self.spikeWaveformIndex):
            # Build waveform
            for i in range(self.totalTSteps):
                polyline[i] = QPointF(
                    xScaleFactor * i + xOffset, yScaleFactor *
                    self.spikeWaveform[(j + 30) % len(self.spikeWaveform)][i] +
                    yOffset)

            # Draw waveform
            painter.setPen(self.scopeColors[colorIndex][index])
            index += 1
            painter.drawPolyline(QPolygonF(polyline))

        # If using a voltage threshold trigger, plot a line at the threshold level.
        if self.voltageTriggerMode:
            painter.setPen(Qt.red)
            painter.drawLine(xOffset,
                             yScaleFactor * self.voltageThreshold + yOffset,
                             xScaleFactor * (self.totalTSteps - 1) + xOffset,
                             yScaleFactor * self.voltageThreshold + yOffset)

        painter.setClipping(False)

        # Don't update the RMS value display every time, or it will change so fast that it
        # will be hard to read.  Only update once every few times we execute this function.
        if self.rmsDisplayPeriod == 0:
            self.rmsDisplayPeriod = 5
            self.savedRms = rms
        else:
            self.rmsDisplayPeriod -= 1

        # Write RMS value to display.
        textBoxWidth = 180
        textBoxHeight = painter.fontMetrics().height()
        painter.setPen(Qt.darkGreen)

        if self.savedRms < 10.0:
            precision = "1"
        else:
            precision = "0"

        painter.drawText(
            self.frame.left() + 6,
            self.frame.top() + 5, textBoxWidth, textBoxHeight,
            Qt.AlignLeft | Qt.AlignTop,
            "RMS:" + ("%." + precision + "f") % self.savedRms + " " +
            constants.QSTRING_MU_SYMBOL + "V")

        self.update()
Exemplo n.º 38
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        redrawRect = event.rect()
        beginRow = redrawRect.top() // self.squareSize
        endRow = redrawRect.bottom() // self.squareSize
        # XXX: do we need to maintain self._column when we have (endColumn -
        # beginColumn)?
        beginColumn = redrawRect.left() // self.squareSize
        endColumn = redrawRect.right() // self.squareSize

        gradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight)
        gradient.setColorAt(0.0, cellHeaderBaseColor)
        gradient.setColorAt(1.0, cellHeaderLineColor)
        dirtyGradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight)
        dirtyGradient.setColorAt(0.0, cellHeaderBaseColor.darker(125))
        dirtyGradient.setColorAt(1.0, cellHeaderLineColor.darker(125))
        markGradient = QLinearGradient(0, 0, 0, self.squareSize-GlyphCellHeaderHeight)

        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):
                key = row * self._columns + column
                if key >= len(self._glyphs): break
                glyph = self._glyphs[key]

                painter.save()
                painter.translate(column * self.squareSize, row * self.squareSize)
                painter.fillRect(0, 0, self.squareSize, self.squareSize, Qt.white)
                # prepare header colors
                brushColor = gradient
                linesColor = cellHeaderHighlightLineColor
                # mark color
                if not glyph.template:
                    if glyph.markColor is not None:
                        markColor = QColor.fromRgbF(*tuple(glyph.markColor))
                        markGradient.setColorAt(1.0, markColor)
                        markGradient.setColorAt(0.0, markColor.lighter(125))
                        painter.fillRect(0, GlyphCellHeaderHeight, self.squareSize,
                              self.squareSize - GlyphCellHeaderHeight, QBrush(markGradient))
                    if glyph.dirty:
                        brushColor = dirtyGradient
                        linesColor = cellHeaderHighlightLineColor.darker(110)

                # header gradient
                painter.fillRect(0, 0, self.squareSize, GlyphCellHeaderHeight,
                    QBrush(brushColor))
                # header lines
                painter.setPen(linesColor)
                minOffset = painter.pen().width()
                # disable antialiasing to avoid lines bleeding over background
                painter.setRenderHint(QPainter.Antialiasing, False)
                painter.drawLine(0, 0, 0, GlyphCellHeaderHeight - 1)
                painter.drawLine(self.squareSize - 2, 0, self.squareSize - 2, GlyphCellHeaderHeight -1)
                painter.setPen(QColor(170, 170, 170))
                painter.drawLine(0, GlyphCellHeaderHeight, self.squareSize, GlyphCellHeaderHeight)
                painter.setRenderHint(QPainter.Antialiasing)
                # header text
                painter.setFont(headerFont)
                painter.setPen(QColor(80, 80, 80))
                name = metrics.elidedText(glyph.name, Qt.ElideRight, self.squareSize - 2)
                painter.drawText(1, 0, self.squareSize - 2, GlyphCellHeaderHeight - minOffset,
                      Qt.TextSingleLine | Qt.AlignCenter, name)
                painter.restore()

                painter.setPen(cellGridColor)
                rightEdgeX = column * self.squareSize + self.squareSize
                bottomEdgeY = row * self.squareSize + self.squareSize
                painter.drawLine(rightEdgeX, row * self.squareSize + 1, rightEdgeX, bottomEdgeY)
                painter.drawLine(rightEdgeX, bottomEdgeY, column * self.squareSize + 1, bottomEdgeY)
                if self._currentDropIndex is not None:
                    painter.setPen(Qt.green)
                    if self._currentDropIndex == key:
                        painter.drawLine(column * self.squareSize, row * self.squareSize,
                            column * self.squareSize, bottomEdgeY)
                    # special-case the end-column
                    elif column == endColumn and self._currentDropIndex == key+1:
                        yPos = self.mapFromGlobal(QCursor.pos()).y()
                        if row == yPos // self.squareSize:
                            painter.drawLine(rightEdgeX - 1, row * self.squareSize,
                                rightEdgeX - 1, bottomEdgeY)

                # selection code
                if key in self._selection:
                    painter.setRenderHint(QPainter.Antialiasing, False)
                    painter.fillRect(column * self.squareSize + 1,
                            row * self.squareSize + 1, self.squareSize - 3,
                            self.squareSize - 3, cellSelectionColor)
                    painter.setRenderHint(QPainter.Antialiasing)

                if not glyph.template:
                    font = glyph.getParent()
                    outline = glyph.getRepresentation("defconQt.QPainterPath")
                    uPM = font.info.unitsPerEm
                    if uPM is None or not uPM > 0:
                        uPM = 1000
                    descender = font.info.descender
                    if descender is None or not descender < 0:
                        descender = -250
                    factor = (self.squareSize-GlyphCellHeaderHeight) / (uPM*(1+2*GlyphCellBufferHeight))
                    x_offset = (self.squareSize-glyph.width*factor)/2
                    # If the glyph overflows horizontally we need to adjust the scaling factor
                    if x_offset < 0:
                        factor *= 1+2*x_offset/(glyph.width*factor)
                        x_offset = 0
                    # TODO: the * 1.8 below is somewhat artificial
                    y_offset = descender*factor * 1.8
                    painter.save()
                    painter.setClipRect(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight,
                          self.squareSize, self.squareSize-GlyphCellHeaderHeight)
                    painter.translate(column * self.squareSize + x_offset, row * self.squareSize + self.squareSize + y_offset)
                    painter.scale(factor, -factor)
                    painter.fillPath(outline, Qt.black)
                    painter.restore()
                else:
                    painter.save()
                    painter.setFont(voidFont)
                    painter.setPen(QPen(Qt.lightGray))
                    rect = QRectF(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight,
                          self.squareSize, self.squareSize-GlyphCellHeaderHeight)
                    # TODO: need to flag template glyphs as to whether they have unicodings or not
                    if glyph.unicode is not None:
                        text = chr(glyph.unicode)
                    else:
                        text = "✌"
                    painter.drawText(rect, Qt.AlignCenter, text)
                    painter.restore()
Exemplo n.º 39
0
 def paintEvent(self, evt):
     """
     Protected method handling paint events.
     
     @param evt paint event (QPaintEvent)
     """
     if self.__grabbing:     # grabWindow() should just get the background
         return
     
     painter = QPainter(self)
     pal = QPalette(QToolTip.palette())
     font = QToolTip.font()
     
     handleColor = pal.color(QPalette.Active, QPalette.Highlight)
     handleColor.setAlpha(160)
     overlayColor = QColor(0, 0, 0, 160)
     textColor = pal.color(QPalette.Active, QPalette.Text)
     textBackgroundColor = pal.color(QPalette.Active, QPalette.Base)
     painter.drawPixmap(0, 0, self.__pixmap)
     painter.setFont(font)
     
     pol = QPolygon(self.__selection)
     if not self.__selection.boundingRect().isNull():
         # Draw outline around selection.
         # Important: the 1px-wide outline is *also* part of the
         # captured free-region
         pen = QPen(handleColor, 1, Qt.SolidLine, Qt.SquareCap,
                    Qt.BevelJoin)
         painter.setPen(pen)
         painter.drawPolygon(pol)
         
         # Draw the grey area around the selection.
         grey = QRegion(self.rect())
         grey = grey - QRegion(pol)
         painter.setClipRegion(grey)
         painter.setPen(Qt.NoPen)
         painter.setBrush(overlayColor)
         painter.drawRect(self.rect())
         painter.setClipRect(self.rect())
         drawPolygon(painter, pol, handleColor)
     
     if self.__showHelp:
         painter.setPen(textColor)
         painter.setBrush(textBackgroundColor)
         self.__helpTextRect = painter.boundingRect(
             self.rect().adjusted(2, 2, -2, -2),
             Qt.TextWordWrap, self.__helpText).translated(
             -self.__desktop.x(), -self.__desktop.y())
         self.__helpTextRect.adjust(-2, -2, 4, 2)
         drawPolygon(painter, self.__helpTextRect, textColor,
                     textBackgroundColor)
         painter.drawText(
             self.__helpTextRect.adjusted(3, 3, -3, -3),
             Qt.TextWordWrap, self.__helpText)
     
     if self.__selection.isEmpty():
         return
     
     # The grabbed region is everything which is covered by the drawn
     # rectangles (border included). This means that there is no 0px
     # selection, since a 0px wide rectangle will always be drawn as a line.
     boundingRect = self.__selection.boundingRect()
     txt = "{0}, {1} ({2} x {3})".format(
         self.__locale.toString(boundingRect.x()),
         self.__locale.toString(boundingRect.y()),
         self.__locale.toString(boundingRect.width()),
         self.__locale.toString(boundingRect.height())
     )
     textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt)
     boundingRect = textRect.adjusted(-4, 0, 0, 0)
     
     polBoundingRect = pol.boundingRect()
     if (textRect.width() <
         polBoundingRect.width() - 2 * self.__handleSize) and \
        (textRect.height() <
         polBoundingRect.height() - 2 * self.__handleSize) and \
        polBoundingRect.width() > 100 and \
        polBoundingRect.height() > 100:
         # center, unsuitable for small selections
         boundingRect.moveCenter(polBoundingRect.center())
         textRect.moveCenter(polBoundingRect.center())
     elif polBoundingRect.y() - 3 > textRect.height() and \
             polBoundingRect.x() + textRect.width() < self.rect().width():
         # on top, left aligned
         boundingRect.moveBottomLeft(
             QPoint(polBoundingRect.x(), polBoundingRect.y() - 3))
         textRect.moveBottomLeft(
             QPoint(polBoundingRect.x() + 2, polBoundingRect.y() - 3))
     elif polBoundingRect.x() - 3 > textRect.width():
         # left, top aligned
         boundingRect.moveTopRight(
             QPoint(polBoundingRect.x() - 3, polBoundingRect.y()))
         textRect.moveTopRight(
             QPoint(polBoundingRect.x() - 5, polBoundingRect.y()))
     elif (polBoundingRect.bottom() + 3 + textRect.height() <
           self.rect().bottom()) and \
             polBoundingRect.right() > textRect.width():
         # at bottom, right aligned
         boundingRect.moveTopRight(
             QPoint(polBoundingRect.right(), polBoundingRect.bottom() + 3))
         textRect.moveTopRight(
             QPoint(polBoundingRect.right() - 2,
                    polBoundingRect.bottom() + 3))
     elif polBoundingRect.right() + textRect.width() + 3 < \
             self.rect().width():
         # right, bottom aligned
         boundingRect.moveBottomLeft(
             QPoint(polBoundingRect.right() + 3, polBoundingRect.bottom()))
         textRect.moveBottomLeft(
             QPoint(polBoundingRect.right() + 5, polBoundingRect.bottom()))
     
     # If the above didn't catch it, you are running on a very
     # tiny screen...
     drawPolygon(painter, boundingRect, textColor, textBackgroundColor)
     painter.drawText(textRect, Qt.AlignHCenter, txt)
     
     if (polBoundingRect.height() > self.__handleSize * 2 and
         polBoundingRect.width() > self.__handleSize * 2) or \
        not self.__mouseDown:
         painter.setBrush(Qt.transparent)
         painter.setClipRegion(QRegion(pol))
         painter.drawPolygon(QPolygon(self.rect()))