Example #1
0
    def layout(self):
        time_fm = QFontMetrics(self.time.font())
        seconds_fm = QFontMetrics(self.seconds.font())

        x = self.rect.left()
        y = self.rect.top()

        self.time.setPos(x, y)
        self.seconds.setPos(x + time_fm.width("00:00") + 20,
                            y + time_fm.ascent() - seconds_fm.ascent())
        self.date.setPos(x, y + time_fm.ascent())
Example #2
0
    def layout(self):
        x = self.rect.left()
        y = self.rect.top()

        fm = QFontMetrics(self.time.font())
        rect = fm.boundingRect("00:00")

        sfm = QFontMetrics(self.seconds.font())

        self.time.setPos(x, y + 20)
        self.seconds.setPos(x + 20 + rect.width(), y + 20 + fm.ascent() - sfm.ascent())

        self.label.setPos(x, y)
Example #3
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     # 背景白色
     painter.fillRect(event.rect(), QBrush(Qt.white))
     # 绘制边缘虚线框
     painter.setPen(Qt.DashLine)
     painter.setBrush(Qt.NoBrush)
     painter.drawRect(self.rect())
     # 随机画条线
     for _ in range(3):
         painter.setPen(QPen(QTCOLORLIST[qrand() % 5], 1, Qt.SolidLine))
         painter.setBrush(Qt.NoBrush)
         painter.drawLine(QPoint(0, qrand() % self.height()),
                          QPoint(self.width(), qrand() % self.height()))
         painter.drawLine(QPoint(qrand() % self.width(), 0),
                          QPoint(qrand() % self.width(), self.height()))
     # 绘制噪点
     painter.setPen(Qt.DotLine)
     painter.setBrush(Qt.NoBrush)
     for _ in range(self.width()):  # 绘制噪点
         painter.drawPoint(QPointF(qrand() % self.width(), qrand() % self.height()))
     # super(WidgetCode, self).paintEvent(event)  # 绘制文字
     # 绘制跳动文字
     metrics = QFontMetrics(self.font())
     x = (self.width() - metrics.width(self.text())) / 2
     y = (self.height() + metrics.ascent() - metrics.descent()) / 2
     for i, ch in enumerate(self.text()):
         index = (self.step + i) % 16
         painter.setPen(TCOLORLIST[qrand() % 6])
         painter.drawText(x, y - ((SINETABLE[index] * metrics.height()) / 400), ch)
         x += metrics.width(ch)
Example #4
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()
Example #5
0
    def paintEvent(self, event):
        sineTable = (
            0,
            38,
            71,
            92,
            100,
            92,
            71,
            38,
            0,
            -38,
            -71,
            -92,
            -100,
            -92,
            -71,
            -38,
        )

        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.width(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()

        painter = QPainter(self)

        for i, ch in enumerate(self.text):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x,
                             y - ((sineTable[index] * metrics.height()) / 400),
                             ch)
            x += metrics.width(ch)
Example #6
0
    def render_text(self, x, y, text, font=QFont('Arial', 50), color=Qt.white,
                    h_align=Qt.AlignLeft, v_align=Qt.AlignBaseline):
        fm = QFontMetrics(font)
        fr = fm.boundingRect(text)

        if h_align == Qt.AlignRight:
            x -= fr.width()
        elif h_align == Qt.AlignHCenter or h_align == Qt.AlignCenter:
            x -= fr.width()/2
        elif h_align == Qt.AlignLeft:
            pass
        else:
            print("WARNING: %r is not a valid option for horizontal text alignment. Set to Qt.AlignLeft." % h_align)

        if v_align == Qt.AlignTop:
            y += fm.ascent()
        elif v_align == Qt.AlignBottom:
            y -= fm.descent()
        elif v_align == Qt.AlignCenter or v_align == Qt.AlignVCenter:
            y += ((fr.height() / 2) - fm.descent())
        elif v_align == Qt.AlignBaseline:
            pass
        else:
            print("WARNING: %r is not a valid option for vertical text alignment. Set to Qt.AlignBaseline." % v_align)

        painter = QPainter(self)
        painter.setPen(color)
        painter.setFont(font)
        painter.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)
        painter.drawText(x, y, text)  # z = pointT4.z + distOverOp / 4
        painter.end()
Example #7
0
 def sizeHint(self):
     fm = QFontMetrics(self.font())
     # FIXME: 暂时不是太懂应该怎样正确的计算 w 和 h
     # 计算 h 的一个原则是让高度正好能够显示一行
     h = max(fm.height() + fm.ascent() - fm.descent(), 14)
     w = self.width() - 4
     opt = QStyleOptionFrame()
     opt.initFrom(self)
     return self.style().sizeFromContents(
         QStyle.CT_LineEdit, opt,
         QSize(w, h).expandedTo(QApplication.globalStrut()), self)
Example #8
0
    def update_adjusted(self, font=None):
        if font is None:
            font = self.font_family.currentFont()

        if self.auto_size.isChecked():
            font_size = self.font_size.value()
            font.setPixelSize(font_size)
            metrics = QFontMetrics(font)
            rect = metrics.boundingRect(self.edit_text.text())
            print('Font:', font.family())
            print('Height:', rect.height(), rect.top(), '<->',
                  rect.bottom(), 'CapHeight:', metrics.capHeight(), 'Ascent:',
                  metrics.ascent(), 'FontSize:', font_size)
            over_ascent = metrics.ascent() - font_size
            print('OverAscent:', over_ascent)
            adjusted_size = font_size - over_ascent
            self.adjusted_size = adjusted_size
            self.adjusted_size_label.setText(
                'Adjusted size: {0}px'.format(adjusted_size))
        else:
            self.adjusted_size_label.setText('')
Example #9
0
    def paint(self, painter, option, qidx):
        self.initStyleOption(option, qidx)

        tags = qidx.sibling(qidx.row(), 0).data(qidx.model().ThreadTagsRole)

        painter.save()
        try:
            if option.state & QStyle.State_Selected:
                painter.setBackground(option.palette.highlight())
            else:
                painter.setBackground(option.palette.base())
            painter.eraseRect(option.rect)

            painter.setClipRect(option.rect)
            painter.translate(option.rect.topLeft())
            painter.setFont(option.font)

            fm = QFontMetrics(option.font)

            x = self.xmargin
            for sz, tag in self._positions(option, 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

            if option.state & QStyle.State_Selected:
                painter.setPen(QPen(option.palette.highlightedText(), 1))
            else:
                painter.setPen(QPen(option.palette.text(), 1))
            painter.drawText(x + self.xpadding, self.ymargin + fm.ascent(),
                             qidx.data())
        finally:
            painter.restore()
Example #10
0
 def sizeHint(self):
     fm = QFontMetrics(self.font())
     # FIXME: 暂时不是太懂应该怎样正确的计算 w 和 h
     # 计算 h 的一个原则是让高度正好能够显示一行
     h = max(fm.height() + fm.ascent() - fm.descent(), 14)
     w = self.width() - 4
     opt = QStyleOptionFrame()
     opt.initFrom(self)
     return self.style().sizeFromContents(
         QStyle.CT_LineEdit,
         opt,
         QSize(w, h).expandedTo(QApplication.globalStrut()),
         self
     )
Example #11
0
class Danmu(QLabel):
    def __init__(self,
                 parent,
                 dmtext,
                 dmcolor,
                 dmstartx,
                 dmstarty,
                 dmfont="Microsoft YaHei"):
        super(Danmu, self).__init__(parent)
        self.dmQfont = QFont(dmfont, 25, 75)  #字体、大小、粗细
        self.setStyleSheet("color:" + dmcolor)
        self.dmtext = dmtext
        self.setText(self.dmtext)
        self.metrics = QFontMetrics(self.dmQfont)
        self.height = self.metrics.height() + 5
        self.setFixedHeight(self.height)
        self.width = self.metrics.width(dmtext) + 4
        self.setFixedWidth(self.width)
        self.setFont(self.dmQfont)

        self.fly = QPropertyAnimation(self, b'pos')  #弹幕飞行动画
        self.fly.setDuration(10000)  #飞行10秒
        self.fly.setStartValue(QtCore.QPoint(dmstartx, dmstarty))
        self.fly.setEndValue(QtCore.QPoint(0 - self.width, dmstarty))
        self.fly.start()
        self.fly.finished.connect(self.deleteLater)

    #为文字添加描边
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.save()
        path = QPainterPath()
        pen = QPen(QColor(0, 0, 0, 230))
        painter.setRenderHint(QPainter.Antialiasing)  #反走样
        pen.setWidth(4)
        length = self.metrics.width(self.dmtext)
        w = self.width
        px = (length - w) / 2
        if px < 0:
            px = -px
        py = (self.height - self.metrics.height()) / 2 + self.metrics.ascent()
        if py < 0:
            py = -py
        path.addText(px - 2, py, self.dmQfont, self.dmtext)
        painter.strokePath(path, pen)
        painter.drawPath(path)
        painter.fillPath(path, QBrush(QColor(255, 255, 255)))
        painter.restore()
        QLabel.paintEvent(self, event)
Example #12
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,
                )
Example #13
0
    def paintEvent(self, event):
        sineTable = (0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38)

        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.width(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()

        painter = QPainter(self)

        for i, ch in enumerate(self.text):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), ch)
            x += metrics.width(ch)
Example #14
0
 def getTextTag(self, id):
     fm = QFontMetrics(self.font)
     svg = "<text "
     if id:
         svg += "id=\"" + id + "\" "
     svg += "x=\"0\" y=\"" + str(fm.ascent()) + "\" "
     svg += "font-family=\"" + self.font.family() + "\" "
     svg += "font-size=\"" + str(self.font.pointSize() * 1.25) + "px\" "
     if self.font.bold():
         svg += "font-weight=\"bold\" "
     if self.font.italic():
         svg += "font-style=\"italic\" "
     svg += "fill=\"" + self.textcolor.name() + "\" "
     svg += "opacity=\"" + str(self.opacity()) + "\" "
     svg += ">"
     svg += self.text
     svg += "</text>"
     return svg
Example #15
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
Example #16
0
    def paintEvent(self, event):
        """This method draws a left sidebar

        :param event: QEvent
        """

        bottom = self.editor.viewport().height()
        font_metrics = QFontMetrics(self.editor.document().defaultFont())
        current_line = self.editor.document().findBlock(
            self.editor.textCursor().position()).blockNumber() + 1
        painter = QPainter(self)
        painter.fillRect(1, 1, self.width(),
                         self.height() - 2, QColor("#e8e8e8"))
        block = self.editor.firstVisibleBlock()
        vpoffset = self.editor.contentOffset()
        line = block.blockNumber()
        painter.setFont(self.editor.document().defaultFont())

        while block.isValid():
            line += 1
            pos = self.editor.blockBoundingGeometry(block).topLeft() + vpoffset
            if pos.y() > bottom:
                break

            # Text bold
            font = painter.font()
            if current_line == line:
                font.setBold(True)
            else:
                font.setBold(False)
            painter.setFont(font)

            if block.isVisible():
                painter.setPen(QColor("#9A9A9A"))
                fm_ascent = font_metrics.ascent()
                fm_descent = font_metrics.descent()
                painter.drawText(self.width() -
                                 font_metrics.width(str(line)) - 3,
                                 pos.y() + fm_ascent + fm_descent, str(line))

            block = block.next()
        painter.end()
        QFrame.paintEvent(self, event)
Example #17
0
 def paintEvent(self, evt: QPaintEvent):
     # default painting, should paint icon
     super(ButtonTextOverIcon, self).paintEvent(evt)
     # draw text over it, only if it not empty string
     if (self._text is not None) and (self._text != ''):
         # calculate the width of text in pixels
         font = self.font()
         font_metrics = QFontMetrics(font)
         text_width = font_metrics.width(self._text)
         text_height = font_metrics.height()
         # calculate text output coordinates centered
         w = self.width()
         h = self.height()
         x = w//2 - text_width//2
         y = h//2 - text_height//2
         # draw text, centered inside window
         painter = QPainter(self)
         y += font_metrics.ascent()  # Note: The y-position is used as the baseline of the font. add it
         self._drawTextShadow(painter, x, y, self._text)
Example #18
0
 def paintEvent(self, x_ev):
     nu_metrics = QFontMetrics(self.font())
     nv_x = int((self.width() - nu_metrics.width(self.wv_text)) / 2)
     nu_y = int(
         (self.height() + nu_metrics.ascent() - nu_metrics.descent()) / 2)
     nu_color = QColor()
     nu_painter = QPainter()
     nu_painter.begin(self)
     nu_tbl_sz = len(self.WC_SINE_TBL)
     for bu2_i, bu2_ch in enumerate(self.wv_text):
         bu2_idx = (self.wv_step + bu2_i) % nu_tbl_sz
         nu_color.setHsv((nu_tbl_sz - 1 - bu2_idx) * nu_tbl_sz, 255, 191)
         nu_painter.setPen(nu_color)
         nu_painter.drawText(
             nv_x, nu_y - int(
                 (self.WC_SINE_TBL[bu2_idx] * nu_metrics.height()) / 400),
             bu2_ch)
         nv_x += nu_metrics.width(bu2_ch)
     nu_painter.end()
Example #19
0
    def paint(self, painter, option, qidx):
        painter.save()
        try:
            painter.setClipRect(option.rect)
            painter.translate(option.rect.topLeft())

            fm = QFontMetrics(option.font)

            if option.state & QStyle.State_Selected:
                painter.setPen(QPen(option.palette.highlightedText(), 1))
            else:
                painter.setPen(QPen(option.palette.text(), 1))

            x = self.xmargin
            for sz, tag in self._positions(option, qidx):
                painter.drawRoundedRect(x, self.ymargin, sz.width() + 2 * self.xpadding, fm.height(), self.radius, self.radius)
                painter.drawText(x + self.xpadding, self.ymargin + fm.ascent(), tag)
                x += sz.width() + self.xmargin + 2 * self.xpadding
        finally:
            painter.restore()
Example #20
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
Example #21
0
    def basic_font_metrics(self, font: QFont) -> BasicFontMetrics:
        """
        Calculates some commonly needed font metrics and returns them in a
        BasicFontMetrics tuple.
        """
        qMetric = QFontMetrics(font)
        info = BasicFontMetrics.make([
            font.pointSizeF(),
            qMetric.height(),
            qMetric.ascent(),
            qMetric.boundingRect("N").height(),
            qMetric.boundingRect("N").width(),
        ])

        LOG.diagnostic("GUI Font Family: %s" % font.family())
        LOG.diagnostic("GUI Font Point Size: %.2f" % info.points)
        LOG.diagnostic("GUI Font Pixel Size: %d" % info.pixels)
        LOG.diagnostic("GUI Base Icon Size: %d" % info.icon_size)
        LOG.diagnostic("Text 'N' Height: %d" % info.n_height)
        LOG.diagnostic("Text 'N' Width: %d" % info.n_width)
        return info
Example #22
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)
Example #23
0
File: Danmu.py Project: afawa/danmu
 def paintEvent(self, QPaintEvent):
     painter = QPainter(self)
     painter.save()
     metrics = QFontMetrics(self.getQFont())
     path = QPainterPath()
     pen = QPen(QColor(0, 0, 0, 230))
     painter.setRenderHint(QPainter.Antialiasing)
     penwidth = 4
     pen.setWidth(penwidth)
     len = metrics.width(self.__Dtext)
     w = self.width()
     px = (len - w) / 2
     if px < 0:
         px = -px
     py = (self.height() - metrics.height()) / 2 + metrics.ascent()
     if py < 0:
         py = -py
     path.addText(px + 2, py + 2, self.getQFont(), self.__Dtext)
     painter.strokePath(path, pen)
     painter.drawPath(path)
     painter.fillPath(path, QBrush(self.getQColor()))
     painter.restore()
Example #24
0
 def paintEvent(self, e):
     super().paintEvent(e)
     if not self._results:
         return
     painter = QPainter(self.viewport())
     option = self.viewOptions()
     painter.setRenderHint(QPainter.Antialiasing)
     fm = QFontMetrics(option.font)
     for _, result in self._results.items():
         index, state = result
         rect = self.rectForIndex(index)
         if state is None:
             text = '😶'
         elif state is True:
             text = '👋'
         else:
             text = '🙁'
         x = rect.width() - 20 + rect.x()
         # 让字垂直居中
         y = (rect.height() + fm.ascent() - fm.descent()) // 2 + rect.y()
         topleft = QPoint(x, y)
         painter.drawText(topleft, text)
Example #25
0
 def paintEvent(self, e):
     super().paintEvent(e)
     if not self._results:
         return
     painter = QPainter(self.viewport())
     option = self.viewOptions()
     painter.setRenderHint(QPainter.Antialiasing)
     fm = QFontMetrics(option.font)
     for row, result in self._results.items():
         index, state = result
         rect = self.rectForIndex(index)
         if state is None:
             text = '😶'
         elif state is True:
             text = '👋'
         else:
             text = '🙁'
         x = rect.width() - 20 + rect.x()
         # 让字垂直居中
         y = (rect.height() + fm.ascent() - fm.descent()) / 2 + rect.y()
         topleft = QPoint(x, y)
         painter.drawText(topleft, text)
Example #26
0
    def draw_text(self, pos, text, font, fg):
        if not text:
            return
        qfont = QFont(font.family)
        qfont.setPixelSize(font.size)
        qfont.setBold(FontStyle.bold in font.style)
        qfont.setItalic(FontStyle.italic in font.style)
        qfont.setStrikeOut(FontStyle.strike in font.style)
        qfont.setUnderline(FontStyle.underline in font.style)
        qfont.setStyleStrategy(QFont.PreferAntialias)
        metrics = QFontMetrics(qfont)

        self.__painter.setFont(qfont)
        self.__set_pen(fg)
        x = pos.x
        y = pos.y + metrics.ascent()
        if '\n' in text:
            height = metrics.height()
            for line in text.split('\n'):
                self.__painter.drawText(QPoint(x, y), line)
                y += height
        else:
            self.__painter.drawText(QPoint(x, y), text)
Example #27
0
    def paint(self, painter, option, qidx):
        painter.save()
        try:
            painter.setClipRect(option.rect)
            painter.translate(option.rect.topLeft())

            fm = QFontMetrics(option.font)

            if option.state & QStyle.State_Selected:
                painter.setPen(QPen(option.palette.highlightedText(), 1))
            else:
                painter.setPen(QPen(option.palette.text(), 1))

            x = self.xmargin
            for sz, tag in self._positions(option, qidx):
                painter.drawRoundedRect(x, self.ymargin,
                                        sz.width() + 2 * self.xpadding,
                                        fm.height(), self.radius, self.radius)
                painter.drawText(x + self.xpadding, self.ymargin + fm.ascent(),
                                 tag)
                x += sz.width() + self.xmargin + 2 * self.xpadding
        finally:
            painter.restore()
Example #28
0
    def paintEvent(self, event):
        page_bottom = self.edit.viewport().height()
        font_metrics = QFontMetrics(self.edit.document().defaultFont())
        current_block = self.edit.document().findBlock(
            self.edit.textCursor().position())
        pattern = self.pat if self.edit.lang == "python" else self.patNotPython

        painter = QPainter(self)
        background = resources.CUSTOM_SCHEME.get(
            'sidebar-background', resources.COLOR_SCHEME['sidebar-background'])
        foreground = resources.CUSTOM_SCHEME.get(
            'sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground'])
        background_selected = resources.CUSTOM_SCHEME.get(
            'sidebar-selected-background',
            resources.COLOR_SCHEME['sidebar-selected-background'])
        foreground_selected = resources.CUSTOM_SCHEME.get(
            'sidebar-selected-foreground',
            resources.COLOR_SCHEME['sidebar-selected-foreground'])
        painter.fillRect(self.rect(), QColor(background))

        block = self.edit.firstVisibleBlock()
        viewport_offset = self.edit.contentOffset()
        line_count = block.blockNumber()
        painter.setFont(self.edit.document().defaultFont())

        xofs = self.width() - self.foldArea
        painter.fillRect(
            xofs, 0, self.foldArea, self.height(),
            QColor(
                resources.CUSTOM_SCHEME.get(
                    'fold-area', resources.COLOR_SCHEME['fold-area'])))

        while block.isValid():
            line_count += 1
            # The top left position of the block in the document
            position = self.edit.blockBoundingGeometry(block).topLeft() + \
                viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # Set the Painter Pen depending on special lines
            painter.setPen(QColor(foreground))
            error = False
            checkers = self._neditable.sorted_checkers
            for items in checkers:
                checker, color, _ = items
                if (line_count - 1) in checker.checks:
                    painter.setPen(QColor(color))
                    font = painter.font()
                    font.setItalic(True)
                    font.setUnderline(True)
                    painter.setFont(font)
                    error = True
                    break

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                painter.fillRect(
                    0,
                    round(position.y()) + font_metrics.descent(), self.width(),
                    font_metrics.ascent() + font_metrics.descent(),
                    QColor(background_selected))

                bold = True
                font = painter.font()
                font.setBold(True)
                if not error:
                    painter.setPen(QColor(foreground_selected))
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            if block.isVisible():
                painter.drawText(
                    self.width() - self.foldArea -
                    font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() +
                    font_metrics.descent() - 1, str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)
            if error:
                font = painter.font()
                font.setItalic(False)
                font.setUnderline(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count

        #Code Folding
        if self.foldArea != self.rightArrowIcon.width():
            polygon = QPolygonF()

            self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.rightArrowIcon.fill(Qt.transparent)
            self.downArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.downArrowIcon.fill(Qt.transparent)

            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25))
            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75))
            polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5))
            iconPainter = QPainter(self.rightArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(
                QColor(
                    resources.CUSTOM_SCHEME.get(
                        'fold-arrow', resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            polygon.clear()
            polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8))
            iconPainter = QPainter(self.downArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(
                QColor(
                    resources.CUSTOM_SCHEME.get(
                        'fold-arrow', resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            self.calculate_docstring_block_fold()

        block = self.edit.firstVisibleBlock()
        while block.isValid():
            position = self.edit.blockBoundingGeometry(
                block).topLeft() + viewport_offset
            #Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            if pattern.match(block.text()) and block.isVisible():
                can_fold = True
                if self.patComment.match(block.text()) and \
                   (block.blockNumber() in self._endDocstringBlocks):
                    can_fold = False

                if can_fold:
                    if block.blockNumber() in self.foldedBlocks:
                        painter.drawPixmap(xofs, round(position.y()),
                                           self.rightArrowIcon)
                    else:
                        painter.drawPixmap(xofs, round(position.y()),
                                           self.downArrowIcon)
            #Add Bookmarks and Breakpoint
            if block.blockNumber() in self.breakpoints:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()), xofs + self.foldArea,
                    round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(255, 11, 11))
                linear_gradient.setColorAt(1, QColor(147, 9, 9))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawEllipse(xofs + 1,
                                    round(position.y()) + 6, self.foldArea - 1,
                                    self.foldArea - 1)
            elif block.blockNumber() in self.bookmarks:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()), xofs + self.foldArea,
                    round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(13, 62, 243))
                linear_gradient.setColorAt(1, QColor(5, 27, 106))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawRoundedRect(xofs + 1,
                                        round(position.y()) + 6,
                                        self.foldArea - 2, self.foldArea - 1,
                                        3, 3)

            block = block.next()

        painter.end()
        super(SidebarWidget, self).paintEvent(event)
Example #29
0
    def __init__(self, theParent):

        self.mainConf = nw.CONFIG
        self.theParent = theParent
        self.theIcons = GuiIcons(self.theParent)
        self.guiPalette = QPalette()
        self.guiPath = "gui"
        self.fontPath = "fonts"
        self.syntaxPath = "syntax"
        self.cssName = "style.qss"
        self.confName = "theme.conf"
        self.themeList = []
        self.syntaxList = []

        # Loaded Theme Settings

        ## Theme
        self.themeName = ""
        self.themeDescription = ""
        self.themeAuthor = ""
        self.themeCredit = ""
        self.themeUrl = ""
        self.themeLicense = ""
        self.themeLicenseUrl = ""

        ## GUI
        self.statNone = [120, 120, 120]
        self.statUnsaved = [200, 15, 39]
        self.statSaved = [2, 133, 37]
        self.helpText = [0, 0, 0]

        # Loaded Syntax Settings

        ## Main
        self.syntaxName = ""
        self.syntaxDescription = ""
        self.syntaxAuthor = ""
        self.syntaxCredit = ""
        self.syntaxUrl = ""
        self.syntaxLicense = ""
        self.syntaxLicenseUrl = ""

        ## Colours
        self.colBack = [255, 255, 255]
        self.colText = [0, 0, 0]
        self.colLink = [0, 0, 0]
        self.colHead = [0, 0, 0]
        self.colHeadH = [0, 0, 0]
        self.colEmph = [0, 0, 0]
        self.colDialN = [0, 0, 0]
        self.colDialD = [0, 0, 0]
        self.colDialS = [0, 0, 0]
        self.colHidden = [0, 0, 0]
        self.colKey = [0, 0, 0]
        self.colVal = [0, 0, 0]
        self.colSpell = [0, 0, 0]
        self.colTagErr = [0, 0, 0]
        self.colRepTag = [0, 0, 0]
        self.colMod = [0, 0, 0]

        # Changeable Settings
        self.guiTheme = None
        self.guiSyntax = None
        self.themeRoot = None
        self.themePath = None
        self.syntaxFile = None
        self.confFile = None
        self.cssFile = None
        self.guiFontDB = QFontDatabase()

        self.loadFonts()
        self.updateFont()
        self.updateTheme()
        self.theIcons.updateTheme()

        self.getIcon = self.theIcons.getIcon
        self.getPixmap = self.theIcons.getPixmap
        self.loadDecoration = self.theIcons.loadDecoration

        # Extract Other Info
        self.guiDPI = qApp.primaryScreen().logicalDotsPerInchX()
        self.guiScale = qApp.primaryScreen().logicalDotsPerInchX() / 96.0
        self.mainConf.guiScale = self.guiScale
        logger.verbose("GUI DPI: %.1f" % self.guiDPI)
        logger.verbose("GUI Scale: %.2f" % self.guiScale)

        # Fonts
        self.guiFont = qApp.font()

        qMetric = QFontMetrics(self.guiFont)
        self.fontPointSize = self.guiFont.pointSizeF()
        self.fontPixelSize = int(round(qMetric.height()))
        self.baseIconSize = int(round(qMetric.ascent()))
        self.textNHeight = qMetric.boundingRect("N").height()
        self.textNWidth = qMetric.boundingRect("N").width()

        # Monospace Font
        self.guiFontFixed = QFont()
        self.guiFontFixed.setPointSizeF(0.95 * self.fontPointSize)
        self.guiFontFixed.setFamily(
            QFontDatabase.systemFont(QFontDatabase.FixedFont).family())

        logger.verbose("GUI Font Family: %s" % self.guiFont.family())
        logger.verbose("GUI Font Point Size: %.2f" % self.fontPointSize)
        logger.verbose("GUI Font Pixel Size: %d" % self.fontPixelSize)
        logger.verbose("GUI Base Icon Size: %d" % self.baseIconSize)
        logger.verbose("Text 'N' Height: %d" % self.textNHeight)
        logger.verbose("Text 'N' Width: %d" % self.textNWidth)

        # Internal Mapping
        self.makeAlert = self.theParent.makeAlert
        self.tr = partial(QCoreApplication.translate, "GuiTheme")

        return
Example #30
0
    def paintEvent(self, event):
        metrics = QFontMetrics(self.font)
        fw = metrics.width("0000000")
        fh = metrics.height()
        ascent = metrics.ascent()

        w, h = self.width(), self.height()

        painter = QPainter(self)
        painter.setFont(self.font)
        blackpen = QPen(Qt.black, 1)
        greypen = QPen(Qt.gray, 1)
        painter.setPen(blackpen)
        fill = QBrush(QColor(255, 255, 255))
        painter.fillRect(QRect(fw, 0, w - fw - 1, h - fh), fill)

        if self.A.shape[1]:
            X, Y = numpy.moveaxis(self.A[:, -w // 2:], 2, 0)
            Ymin = min(0, Y.min())
            Ymax = Y.max()

            maxticks = int((h - fh) / (1.5 * fh))

            for k in count(0):
                if 2**k * maxticks >= Ymax:
                    break

            ticks = Ymax / 2**k
            ticks = int(ticks + (-ticks) % 1)
            Ymax = ticks * 2**k

            Xmax = X.max()
            Xmin = Xmax - w / 2

            for x in range(int(Xmin + (120 - Xmin) % 120), int(Xmax), 120):
                if x < 0:
                    continue
                u = (w - fw) * (x - Xmin) / (Xmax - Xmin) + fw
                painter.setPen(greypen)
                painter.drawLine(u, 0, u, h - fh)

                painter.setPen(blackpen)
                sw = metrics.width(str(x))
                if u - sw // 2 > fw and u + sw // 2 < w:
                    painter.drawText(u - sw // 2, h, str(x))

            for y in range(0, int(Ymax), 2**k):
                v = h - fh - (h - fh) * (y - Ymin) / (Ymax - Ymin)
                painter.setPen(greypen)
                painter.drawLine(fw, v, w, v)

                painter.setPen(blackpen)
                sw = metrics.width(str(y))
                painter.drawText(fw - sw - 4, v + ascent / 3, str(y))

            for pen, row in zip(self.pens, self.A):
                X, Y = row[-w // 2:].transpose()
                U = (w - fw) * (X - Xmin) / (Xmax - Xmin) + fw
                V = h - fh - (h - fh) * (Y - Ymin) / (Ymax - Ymin)

                painter.setPen(pen)
                path = QPainterPath()
                painter.setRenderHint(QPainter.Antialiasing)
                path.moveTo(U[0], V[0])

                for x, y in zip(U[1:], V[1:]):
                    path.lineTo(x, y)

                painter.drawPath(path)

        painter.setPen(blackpen)
        painter.drawRect(QRect(fw, 0, w - fw - 1, h - fh))
Example #31
0
    def __init__(self):

        self.mainConf = novelwriter.CONFIG
        self.iconCache = GuiIcons(self)

        # Loaded Theme Settings
        # =====================

        # Theme
        self.themeName = ""
        self.themeDescription = ""
        self.themeAuthor = ""
        self.themeCredit = ""
        self.themeUrl = ""
        self.themeLicense = ""
        self.themeLicenseUrl = ""

        # GUI
        self.statNone = [120, 120, 120]
        self.statUnsaved = [200, 15, 39]
        self.statSaved = [2, 133, 37]
        self.helpText = [0, 0, 0]

        # Loaded Syntax Settings
        # ======================

        # Main
        self.syntaxName = ""
        self.syntaxDescription = ""
        self.syntaxAuthor = ""
        self.syntaxCredit = ""
        self.syntaxUrl = ""
        self.syntaxLicense = ""
        self.syntaxLicenseUrl = ""

        # Colours
        self.colBack = [255, 255, 255]
        self.colText = [0, 0, 0]
        self.colLink = [0, 0, 0]
        self.colHead = [0, 0, 0]
        self.colHeadH = [0, 0, 0]
        self.colEmph = [0, 0, 0]
        self.colDialN = [0, 0, 0]
        self.colDialD = [0, 0, 0]
        self.colDialS = [0, 0, 0]
        self.colHidden = [0, 0, 0]
        self.colKey = [0, 0, 0]
        self.colVal = [0, 0, 0]
        self.colSpell = [0, 0, 0]
        self.colError = [0, 0, 0]
        self.colRepTag = [0, 0, 0]
        self.colMod = [0, 0, 0]

        # Changeable Settings
        self.guiTheme = None
        self.guiSyntax = None
        self.syntaxFile = None
        self.cssFile = None
        self.guiFontDB = QFontDatabase()

        # Class Setup
        # ===========

        self._guiPalette = QPalette()
        self._themeList = []
        self._syntaxList = []
        self._availThemes = {}
        self._availSyntax = {}

        self._listConf(self._availSyntax,
                       os.path.join(self.mainConf.dataPath, "syntax"))
        self._listConf(self._availSyntax,
                       os.path.join(self.mainConf.assetPath, "syntax"))
        self._listConf(self._availThemes,
                       os.path.join(self.mainConf.dataPath, "themes"))
        self._listConf(self._availThemes,
                       os.path.join(self.mainConf.assetPath, "themes"))

        self.updateFont()
        self.updateTheme()
        self.iconCache.updateTheme()

        # Icon Functions
        self.getIcon = self.iconCache.getIcon
        self.getPixmap = self.iconCache.getPixmap
        self.getItemIcon = self.iconCache.getItemIcon
        self.loadDecoration = self.iconCache.loadDecoration

        # Extract Other Info
        self.guiDPI = qApp.primaryScreen().logicalDotsPerInchX()
        self.guiScale = qApp.primaryScreen().logicalDotsPerInchX() / 96.0
        self.mainConf.guiScale = self.guiScale
        logger.verbose("GUI DPI: %.1f", self.guiDPI)
        logger.verbose("GUI Scale: %.2f", self.guiScale)

        # Fonts
        self.guiFont = qApp.font()

        qMetric = QFontMetrics(self.guiFont)
        self.fontPointSize = self.guiFont.pointSizeF()
        self.fontPixelSize = int(round(qMetric.height()))
        self.baseIconSize = int(round(qMetric.ascent()))
        self.textNHeight = qMetric.boundingRect("N").height()
        self.textNWidth = qMetric.boundingRect("N").width()

        # Monospace Font
        self.guiFontFixed = QFont()
        self.guiFontFixed.setPointSizeF(0.95 * self.fontPointSize)
        self.guiFontFixed.setFamily(
            QFontDatabase.systemFont(QFontDatabase.FixedFont).family())

        logger.verbose("GUI Font Family: %s", self.guiFont.family())
        logger.verbose("GUI Font Point Size: %.2f", self.fontPointSize)
        logger.verbose("GUI Font Pixel Size: %d", self.fontPixelSize)
        logger.verbose("GUI Base Icon Size: %d", self.baseIconSize)
        logger.verbose("Text 'N' Height: %d", self.textNHeight)
        logger.verbose("Text 'N' Width: %d", self.textNWidth)

        return
Example #32
0
    def paintEvent(self, event):
        if self.p:
            if self.p.isNull():
                vid_info = "{}".format(self.parent.video)
                self.logger.warning(
                    "QPixmap self.p was NULL, replacing with 'Thumbnail N/A' image! Video: {}"
                    .format(vid_info))
                self.p = QPixmap(THUMBNAIL_NA_PATH)

            painter = QPainter(self)

            if read_config('Gui', 'keep_thumb_ar'):
                thumb = self.p.scaled(self.width(), self.height(),
                                      Qt.KeepAspectRatio,
                                      Qt.SmoothTransformation)
                painter.drawPixmap(0, 0, thumb)
            else:
                thumb = self
                painter.drawPixmap(thumb.rect(), thumb.p)

            # Overlay video duration on thumbnail
            font = QFont()
            font.fromString(
                read_config("Fonts",
                            "video_thumbnail_overlay_font",
                            literal_eval=False))

            pen = QPen(Qt.white)
            painter.setPen(pen)
            painter.setFont(font)

            duration_right_padding = read_config('GridView',
                                                 'duration_right_padding')
            duration_bottom_padding = read_config('GridView',
                                                  'duration_bottom_padding')

            point = QPoint(thumb.width() - duration_right_padding,
                           thumb.height() - duration_bottom_padding)
            metrics = QFontMetrics(font)
            duration_string = format(self.parent.video.duration)
            # Find out the width of the text
            text_width = metrics.width(duration_string)
            # Work out the max height the text can be
            text_height = metrics.descent() + metrics.ascent()
            # Add a padding of 8px (4px on left, 4px on right) for width
            rect_width = text_width + 8
            # Add a padding of 4px (2px on top, 2px on bottom) for height
            rect_height = text_height + 4
            # Create a rectangle
            # point starts at the bottom right so we need to use negative sizes
            # because we need to move closer to 0,0 again
            rect = QRect(point, QSize(-rect_width, -rect_height))
            painter.fillRect(rect, QBrush(QColor(0, 0, 0, 180)))
            painter.drawText(rect, Qt.AlignCenter, duration_string)

            # Overlay captions (if any) on thumbnail    # FIXME: Replace with something better like a small icon
            if self.parent.video.has_caption and read_config(
                    'GridView', 'show_has_captions'):
                pen = QPen(Qt.white)
                painter.setPen(pen)
                painter.setFont(font)

                captions_left_padding = read_config('GridView',
                                                    'captions_left_padding')
                captions_bottom_padding = read_config(
                    'GridView', 'captions_bottom_padding')

                point = QPoint(captions_left_padding,
                               thumb.height() - captions_bottom_padding)
                metrics = QFontMetrics(font)
                text_width = metrics.width("captions")
                text_height = metrics.descent() + metrics.ascent()
                rect_width = text_width + 8
                rect_height = text_height + 4

                rect = QRect(point, QSize(rect_width, -rect_height))
                painter.fillRect(rect, QBrush(QColor(0, 0, 0, 180)))
                painter.drawText(rect, Qt.AlignCenter, "captions")

            if self.parent.video.definition == "sd" and read_config(
                    'GridView', 'show_sd_warning'):
                pen = QPen(Qt.red)
                painter.setPen(pen)
                painter.setFont(font)

                sd_left_padding = 4
                sd_top_padding = 4

                point = QPoint(sd_left_padding, sd_top_padding)
                metrics = QFontMetrics(font)
                text_width = metrics.width("SD")
                text_height = metrics.descent() + metrics.ascent()
                rect_width = text_width + 4
                rect_height = text_height + 4

                rect = QRect(point, QSize(rect_width, rect_height))
                painter.fillRect(rect, QBrush(QColor(0, 0, 0, 180)))
                painter.drawText(rect, Qt.AlignCenter, "SD")

            self.add_overlay(painter, thumb)
Example #33
0
class CharacterWidget(QWidget):

    characterSelected = pyqtSignal(str)

    def __init__(self, parent):
        super(CharacterWidget, self).__init__(parent)
        self.parent = parent
        self.color_hl = Qt.gray
        self.cell_size = 38
        self.columns = 16
        self.lastKey = -1
        self.currentKey = -1
        self.pressedKey = None
        self.setMouseTracking(True)
        self.setStyleSheet('''
            QToolTip {
                color: black;
                background-color: cornsilk;
                border: 1px;
                font-size: 14px;
            }''')

        self.fontMetrics = QFontMetrics(self.parent.big_font)

    def sizeHint(self):
        return QSize(self.columns * self.cell_size,
                     (131072 / self.columns) * self.cell_size)

    def mouseMoveEvent(self, event):
        if self.pressedKey:
            return
        widgetPosition = self.mapFromGlobal(event.globalPos())
        self.currentKey = (widgetPosition.y() // self.cell_size) * \
            self.columns + widgetPosition.x() // self.cell_size

        if self.currentKey != self.lastKey:
            self.lastKey = self.currentKey
            name = self.parent.table._symbol_list[self.currentKey]
            if name == "no info":
                QToolTip.hideText()
            else:
                info_str = (
                    '<i style="text-align:center">{0}</i>'
                    '<pre style="text-align:center">Hex: {1:04X} | Dec: {1}</pre>'
                    '<p style="font-size:48px;text-align:center">{2}</p>'
                ).format(name, self.currentKey, chr(self.currentKey))
                # info_str = '{0}\nU+{1:04X} | Dec:{1}'.format(name, self.currentKey)
                QToolTip.showText(event.globalPos(), info_str, self)
            self.update()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            key_ch = chr(self.lastKey)
            if self.parent.table._symbol_list[self.currentKey] != "no info":
                self.pressedKey = self.currentKey
                self.characterSelected.emit(key_ch)
            self.update()
        else:
            super(CharacterWidget, self).mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        self.currentKey = (event.y() // self.cell_size) * \
            self.columns + event.x() // self.cell_size
        self.pressedKey = None
        self.update()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(event.rect(), Qt.white)
        painter.setFont(self.parent.big_font)

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

        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):
                key = row * self.columns + column
                key_ch = chr(key)
                if self.parent.table._symbol_list[key] == "no info":
                    continue

                x, y = column * self.cell_size, row * self.cell_size

                painter.setPen(Qt.lightGray)
                painter.drawRect(x, y, self.cell_size, self.cell_size)

                if key == self.currentKey:
                    painter.fillRect(x + 1, y + 1, self.cell_size - 1,
                                     self.cell_size - 1, self.color_hl)

                if key == self.pressedKey:
                    painter.fillRect(x + 1, y + 1, self.cell_size,
                                     self.cell_size, Qt.black)

                    painter.setPen(self.color_hl)
                    painter.drawText(
                        x +
                        (self.cell_size - self.fontMetrics.width(key_ch)) / 2,
                        y + 6 + self.fontMetrics.ascent(), key_ch)
                else:
                    painter.setPen(Qt.black)
                    painter.drawText(
                        x +
                        (self.cell_size - self.fontMetrics.width(key_ch)) / 2,
                        y + 6 + self.fontMetrics.ascent(), key_ch)
Example #34
0
    def paintEvent(self, event):
        page_bottom = self.edit.viewport().height()
        font_metrics = QFontMetrics(self.edit.document().defaultFont())
        current_block = self.edit.document().findBlock(
            self.edit.textCursor().position())
        pattern = self.pat if self.edit.lang == "python" else self.patNotPython

        painter = QPainter(self)
        background = resources.CUSTOM_SCHEME.get('sidebar-background',
            resources.COLOR_SCHEME['sidebar-background'])
        foreground = resources.CUSTOM_SCHEME.get('sidebar-foreground',
            resources.COLOR_SCHEME['sidebar-foreground'])
        pep8color = resources.CUSTOM_SCHEME.get('pep8-underline',
            resources.COLOR_SCHEME['pep8-underline'])
        errorcolor = resources.CUSTOM_SCHEME.get('error-underline',
            resources.COLOR_SCHEME['error-underline'])
        migrationcolor = resources.CUSTOM_SCHEME.get('migration-underline',
            resources.COLOR_SCHEME['migration-underline'])
        painter.fillRect(self.rect(), QColor(background))

        block = self.edit.firstVisibleBlock()
        viewport_offset = self.edit.contentOffset()
        line_count = block.blockNumber()
        painter.setFont(self.edit.document().defaultFont())
        while block.isValid():
            line_count += 1
            # The top left position of the block in the document
            position = self.edit.blockBoundingGeometry(block).topLeft() + \
                viewport_offset
            # Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            # Set the Painter Pen depending on special lines
            error = False
            if settings.CHECK_STYLE and \
               ((line_count - 1) in self._pep8Lines):
                painter.setPen(QColor(pep8color))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.FIND_ERRORS and \
                 ((line_count - 1) in self._errorsLines):
                painter.setPen(QColor(errorcolor))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            elif settings.SHOW_MIGRATION_TIPS and \
                 ((line_count - 1) in self._migrationLines):
                painter.setPen(QColor(migrationcolor))
                font = painter.font()
                font.setItalic(True)
                font.setUnderline(True)
                painter.setFont(font)
                error = True
            else:
                painter.setPen(QColor(foreground))

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            if block.isVisible():
                painter.drawText(self.width() - self.foldArea -
                    font_metrics.width(str(line_count)) - 3,
                    round(position.y()) + font_metrics.ascent() +
                    font_metrics.descent() - 1,
                    str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)
            if error:
                font = painter.font()
                font.setItalic(False)
                font.setUnderline(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count

        #Code Folding
        xofs = self.width() - self.foldArea
        painter.fillRect(xofs, 0, self.foldArea, self.height(),
                QColor(resources.CUSTOM_SCHEME.get('fold-area',
                resources.COLOR_SCHEME['fold-area'])))
        if self.foldArea != self.rightArrowIcon.width():
            polygon = QPolygonF()

            self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.rightArrowIcon.fill(Qt.transparent)
            self.downArrowIcon = QPixmap(self.foldArea, self.foldArea)
            self.downArrowIcon.fill(Qt.transparent)

            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25))
            polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75))
            polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5))
            iconPainter = QPainter(self.rightArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

            polygon.clear()
            polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4))
            polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8))
            iconPainter = QPainter(self.downArrowIcon)
            iconPainter.setRenderHint(QPainter.Antialiasing)
            iconPainter.setPen(Qt.NoPen)
            iconPainter.setBrush(QColor(
                resources.CUSTOM_SCHEME.get('fold-arrow',
                resources.COLOR_SCHEME['fold-arrow'])))
            iconPainter.drawPolygon(polygon)

        block = self.edit.firstVisibleBlock()
        while block.isValid():
            position = self.edit.blockBoundingGeometry(
                block).topLeft() + viewport_offset
            #Check if the position of the block is outside of the visible area
            if position.y() > page_bottom:
                break

            if pattern.match(block.text()) and block.isVisible():
                if block.blockNumber() in self._foldedBlocks:
                    painter.drawPixmap(xofs, round(position.y()),
                        self.rightArrowIcon)
                else:
                    painter.drawPixmap(xofs, round(position.y()),
                        self.downArrowIcon)
            #Add Bookmarks and Breakpoint
            elif block.blockNumber() in self._breakpoints:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(255, 11, 11))
                linear_gradient.setColorAt(1, QColor(147, 9, 9))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawEllipse(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 1, self.foldArea - 1)
            elif block.blockNumber() in self._bookmarks:
                linear_gradient = QLinearGradient(
                    xofs, round(position.y()),
                    xofs + self.foldArea, round(position.y()) + self.foldArea)
                linear_gradient.setColorAt(0, QColor(13, 62, 243))
                linear_gradient.setColorAt(1, QColor(5, 27, 106))
                painter.setRenderHints(QPainter.Antialiasing, True)
                painter.setPen(Qt.NoPen)
                painter.setBrush(QBrush(linear_gradient))
                painter.drawRoundedRect(
                    xofs + 1,
                    round(position.y()) + 6,
                    self.foldArea - 2, self.foldArea - 1,
                    3, 3)

            block = block.next()# block = next(block)

        painter.end()
        super(SidebarWidget, self).paintEvent(event)
Example #35
0
 def fire(self):
     stdout = subprocess.run(["pgrep", "-i", "thunderbird"],
                             stdout=subprocess.PIPE).stdout.decode('UTF-8')
     if not stdout: sys.exit()
     if self.badprofile:
         self.label_accountwarrning.setText(
             'ERROR! Please Fix Account List')
         self.label_accountwarrning.setStyleSheet('color: red')
         self.label_accountwarrning.show()
         self.tabWidget.setCurrentIndex(1)
         self.tray_icon.showMessage('TBtray Profile Warning',
                                    'Please setup account profiles',
                                    QSystemTrayIcon.Critical)
         self.timetriggercheck.start(15000)
         return
     self.timetriggercheck.stop()
     if self.popup.textBrowser.INTRAY:
         self.INTRAY = False
         self.popup.textBrowser.INTRAY = False
     if not self.windowid:
         stdout = subprocess.run(
             ["wmctrl", '-lx'],
             stdout=subprocess.PIPE).stdout.decode('UTF-8')
         idx = re.findall('(\dx\w+)..0 Mail\.Thunderbird', str(stdout))
         if idx:
             self.windowid = idx[0]
             self.popup.textBrowser.windowid = self.windowid
             print('grabbed window ' + idx[0])
     if self.checkbox_minimizetotray.isChecked() and not self.INTRAY:
         stdout = subprocess.run(
             [
                 "xdotool", "search", "--onlyvisible", "--class",
                 self.winclass
             ],
             stdout=subprocess.PIPE).stdout.decode('UTF-8')
         if not stdout and self.windowid:
             subprocess.run([
                 'wmctrl', '-i', '-r',
                 str(self.windowid), '-b', 'add,skip_taskbar'
             ])
             self.INTRAY = True
     for profile in self.profiles:
         if os.path.getmtime(profile) > self.lastmtime:
             self.lastmtime = os.path.getmtime(profile)
             self.matches = 0
             for profile2 in self.profiles:
                 if not os.path.isfile(profile2): continue
                 filetext = subprocess.run(
                     ["tail", "-n", "2000", profile2],
                     stdout=subprocess.PIPE).stdout.decode('UTF-8')
                 matchesx = re.findall('\^A2=(\w+)', filetext)
                 if matchesx: self.matches += int(matchesx[-1], 16)
             if self.matches > 0:
                 if self.checkbox_showcount.isChecked():
                     iconpixmap = QtGui.QPixmap(self.notifyicon)
                     count = str(self.matches)
                     pixmap = QPixmap(iconpixmap.width(),
                                      iconpixmap.height())
                     fontsize = self.findfontsize(count, pixmap)
                     font = QFont("Arial", fontsize)
                     painter = QPainter()
                     pixmap.fill(Qt.transparent)
                     painter.begin(pixmap)
                     painter.setFont(font)
                     painter.setOpacity(0.3)
                     painter.drawPixmap(iconpixmap.rect(), iconpixmap)
                     painter.setOpacity(1.0)
                     painter.setPen(QColor(self.colour))
                     fm = QFontMetrics(font)
                     painter.drawText(
                         int((pixmap.width() - fm.width(count)) / 2),
                         int((pixmap.height() - fm.height()) / 2 +
                             fm.ascent() + 1), count)
                     painter.end()
                     self.tray_icon.setIcon(QtGui.QIcon(pixmap))
                 else:
                     self.tray_icon.setIcon(QtGui.QIcon(self.notifyicon))
                 if not self.badprofile:
                     self.popup.fire(self.profiles, self.matches)
             else:
                 self.tray_icon.setIcon(QtGui.QIcon(self.defaulticon))
             break
     self.timetriggercheck.start(1000)