コード例 #1
0
ファイル: album.py プロジェクト: jizongFox/FeelUOwn
 def paint(self, painter, option, index):
     painter.save()
     painter.setRenderHint(QPainter.Antialiasing)
     rect = option.rect
     text_rect_height = 30
     cover_spacing = 0
     text_y = rect.y() + rect.height() - text_rect_height
     cover_height = rect.height() - text_rect_height
     cover_width = rect.width() - cover_spacing
     cover_x = rect.x() + cover_spacing // 2
     cover_y = rect.y()
     text_rect = QRectF(rect.x(), text_y + 5, rect.width(), text_rect_height)
     obj = index.data(Qt.DecorationRole)
     if obj is None:
         painter.restore()
         return
     elif isinstance(obj, QColor):
         color = obj
         brush = QBrush(color)
         painter.setBrush(brush)
         painter.drawRect(cover_x, cover_y, cover_width, cover_height)
     else:
         pixmap = obj.scaledToWidth(cover_width, Qt.SmoothTransformation)
         painter.drawPixmap(cover_x, cover_y, pixmap)
     option = QTextOption()
     option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     album_name = index.data(Qt.DisplayRole)
     painter.drawText(text_rect, album_name, option)
     painter.restore()
コード例 #2
0
ファイル: file_item_renderer.py プロジェクト: Grumbel/dirtool
    def paint_detail_view(self, painter: QPainter) -> None:
        self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(), self.tile_rect.height())

        self.paint_thumbnail(painter)

        lst = ([self.fileinfo.basename(), bytefmt.humanize(self.fileinfo.size())] +
               list(self.make_text()))

        text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter)
        text_option.setWrapMode(QTextOption.NoWrap)

        total_width = self.tile_rect.width() - self.thumbnail_rect.width() - 8

        widths = [60, 10, 10, 10, 10, 10]
        x = self.thumbnail_rect.width() + 4
        for idx, text in enumerate(lst[:-1]):
            if idx != 0:
                text_option.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

            width = total_width * (widths[idx] / 100)
            painter.drawText(QRectF(x, 0,
                                    width, self.tile_rect.height()),
                             text,
                             text_option)
            x += width
コード例 #3
0
ファイル: docviewer.py プロジェクト: johnblommers/novelWriter
    def initViewer(self):
        """Set editor settings from main config.
        """

        self._makeStyleSheet()

        # Set Font
        theFont = QFont()
        if self.mainConf.textFont is None:
            # If none is defined, set the default back to config
            self.mainConf.textFont = self.qDocument.defaultFont().family()
        theFont.setFamily(self.mainConf.textFont)
        theFont.setPointSize(self.mainConf.textSize)
        self.setFont(theFont)

        docPalette = self.palette()
        docPalette.setColor(QPalette.Base, QColor(*self.theTheme.colBack))
        docPalette.setColor(QPalette.Text, QColor(*self.theTheme.colText))
        self.setPalette(docPalette)

        self.qDocument.setDocumentMargin(self.mainConf.textMargin)
        theOpt = QTextOption()
        if self.mainConf.doJustify:
            theOpt.setAlignment(Qt.AlignJustify)
        self.qDocument.setDefaultTextOption(theOpt)

        # If we have a document open, we should reload it in case the font changed
        if self.theHandle is not None:
            tHandle = self.theHandle
            self.clearViewer()
            self.loadText(tHandle)

        return True
コード例 #4
0
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.setPen(Qt.NoPen)
        qp.setBrush(self.brushes[1024])
        qp.drawRoundedRect(self.resetRect,5,5)
        qp.setPen(QColor(0xf9f6f2))
        qp.setFont(QFont("Thoma",26))
        qp.drawText(self.resetRect, "Reset", QTextOption(Qt.AlignHCenter|Qt.AlignVCenter))
        qp.setPen(QColor(0x776e65))
        qp.setFont(QFont("Thoma",13))
        qp.drawText(self.descriptionRect,"Join the numbers og get to the 2048 title!", QTextOption(Qt.AlignHCenter|Qt.AlignVCenter))
        for i in range(4):
            for j in range(4):
                rect=QRectF(10+j*100, 110+i*100, 80, 80)
                qp.setPen(Qt.NoPen)
                #qp.setBrush(QColor(255,80,0,160))
                qp.setBrush(self.brushes[self.player1.a[i,j]])
                qp.drawRoundedRect(rect, 5, 5)
                
                if self.player1.a[i,j] < 16:
                    qp.setPen(QColor(0x776e65))
                else:
                    qp.setPen(QColor(0xf9f6f2))
                if self.player1.a[i,j] > 512:
                	qp.setFont(QFont("Tahoma",30))
                elif self.player1.a[i,j] > 64:
                	qp.setFont(QFont("Tahoma",40))
                else:
	                qp.setFont(QFont("Tahoma",50))
                if self.player1.a[i,j] != 0:
                	qp.drawText(rect, str(self.player1.a[i,j]), QTextOption(Qt.AlignHCenter|Qt.AlignVCenter))           
        qp.end()
コード例 #5
0
    def paint(self, painter, option, index):
        """Paints the amount within the bounding box provided in the option parameter.

        Draws the currency left aligned and the value of the model amount right aligned.
        Some spacing between with left and right padding is also utilized.

        Args:
            painter - QPainter
            option - QStyleOptionViewItem
            index - QModelIndex in the model
        """
        column_data = self._getDataFromIndex(index)
        if column_data is None:
            return
        option = QStyleOptionViewItem(option)
        painter.setFont(option.font)
        cur_width, val_width = self._getAmountTextWidths(column_data, option)
        font_height = option.fontMetrics.height()
        do_paint_currency = cur_width > 0
        is_selected = bool(option.state & QStyle.State_Selected)
        is_active = bool(option.state & QStyle.State_Active)
        palette_active = QPalette.Active if is_active else QPalette.Inactive
        palette_text = QPalette.HighlightedText if is_selected else QPalette.Text
        pen_color = option.palette.color(palette_active, palette_text)
        painter.setPen(pen_color)

        if do_paint_currency:
            painter.drawText(
                QRectF(4 + option.rect.left(), option.rect.top(), cur_width,
                       font_height), column_data.currency,
                QTextOption(Qt.AlignVCenter))
        painter.drawText(
            QRectF(option.rect.right() - val_width - 5, option.rect.top(),
                   val_width, font_height), column_data.value,
            QTextOption(Qt.AlignVCenter))
コード例 #6
0
    def __init__(self, theParent, theProject):
        QTextBrowser.__init__(self)

        logger.debug("Initialising DocViewer ...")

        # Class Variables
        self.mainConf = nw.CONFIG
        self.theProject = theProject
        self.theParent = theParent
        self.theTheme = theParent.theTheme
        self.theHandle = None

        self.qDocument = self.document()
        self.setMinimumWidth(300)
        self.setOpenExternalLinks(False)
        self.initViewer()

        theOpt = QTextOption()
        if self.mainConf.doJustify:
            theOpt.setAlignment(Qt.AlignJustify)
        self.qDocument.setDefaultTextOption(theOpt)

        self.anchorClicked.connect(self._linkClicked)
        self.setFocusPolicy(Qt.StrongFocus)

        logger.debug("DocViewer initialisation complete")

        return
コード例 #7
0
 def __init__(self, parent=None):
     super(TagTextEdit, self).__init__(parent)
     self.is_undoing = False
     self.setAcceptRichText(False)
     # self.setUndoRedoEnabled(False)
     option = QTextOption()
     option.setFlags(QTextOption.ShowTabsAndSpaces | QTextOption.ShowLineAndParagraphSeparators)
     self.document().setDefaultTextOption(option)
コード例 #8
0
ファイル: EditorWidget.py プロジェクト: afester/CodeSamples
 def toggleNonprintable(self):
     if self.actionsSelector.nonprintableAction.isChecked():
         option = QTextOption()
         option.setFlags(QTextOption.ShowTabsAndSpaces | QTextOption.ShowLineAndParagraphSeparators)
         self.editView.document().setDefaultTextOption(option)
     else:
         option = QTextOption()
         self.editView.document().setDefaultTextOption(option)
コード例 #9
0
    def initViewer(self):
        """Set editor settings from main config.
        """
        self._makeStyleSheet()

        # Set Font
        theFont = QFont()
        if self.mainConf.textFont is None:
            # If none is defined, set the default back to config
            self.mainConf.textFont = self.document().defaultFont().family()
        theFont.setFamily(self.mainConf.textFont)
        theFont.setPointSize(self.mainConf.textSize)
        self.setFont(theFont)

        # Set the widget colours to match syntax theme
        mainPalette = self.palette()
        mainPalette.setColor(QPalette.Window, QColor(*self.mainTheme.colBack))
        mainPalette.setColor(QPalette.Base, QColor(*self.mainTheme.colBack))
        mainPalette.setColor(QPalette.Text, QColor(*self.mainTheme.colText))
        self.setPalette(mainPalette)

        docPalette = self.viewport().palette()
        docPalette.setColor(QPalette.Base, QColor(*self.mainTheme.colBack))
        docPalette.setColor(QPalette.Text, QColor(*self.mainTheme.colText))
        self.viewport().setPalette(docPalette)

        self.docHeader.matchColours()
        self.docFooter.matchColours()

        # Set default text margins
        self.document().setDocumentMargin(0)
        theOpt = QTextOption()
        if self.mainConf.doJustify:
            theOpt.setAlignment(Qt.AlignJustify)
        self.document().setDefaultTextOption(theOpt)

        # Scroll bars
        if self.mainConf.hideVScroll:
            self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        else:
            self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        if self.mainConf.hideHScroll:
            self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        else:
            self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        # Refresh the tab stops
        if self.mainConf.verQtValue >= 51000:
            self.setTabStopDistance(self.mainConf.getTabWidth())
        else:
            self.setTabStopWidth(self.mainConf.getTabWidth())

        # If we have a document open, we should reload it in case the font changed
        if self._docHandle is not None:
            self.reloadText()

        return True
コード例 #10
0
    def DrawFixedScale(self):
        self.FixOverlays()

        if self.fixedscaleCheck.isChecked() and self.camOpen:
            scaleColor = QColor(220, 220, 220, 255)
            linewidth = 2
            basesize = int(np.round(self.camView.width()/2))
            midtickh1 = 10
            midtickh2 = 6
            ratioView = self.camView.width()/self.camView.height()
            ratioFrame = self.camThread.cam.frameW/self.camThread.cam.frameH
            scale = 1
            if ratioView < ratioFrame:
                scale = self.camThread.cam.frameW/self.camView.width()
            else:
                scale = self.camThread.cam.frameH/self.camView.height()
            micronScale = basesize*scale/self.microcalSpin.value()
            if micronScale <= 10:
                micronScale = int(np.round(micronScale))
            elif micronScale < 100:
                micronScale = 10*int(np.round(micronScale/10))
            else:
                micronScale = 100*int(np.round(micronScale/100))
            roundsize = int(np.round(micronScale*self.microcalSpin.value()/scale))
            posI = int(np.round((self.camView.width()/2 - roundsize/2)))
            posF = int(np.round((self.camView.width()/2 + roundsize/2)))
            bottom = self.camView.height() - midtickh1*2
            posmidtick = int(np.round(self.camView.width()/2)) - (int(np.round(linewidth/2)))
            posquartertick1 = posmidtick + int(np.round(roundsize/4)) - (int(np.round(linewidth/2)))
            posquartertick2 = posmidtick - int(np.round(roundsize/4)) - (int(np.round(linewidth/2)))
            labelHeight = int(np.round(midtickh1*6.5))

            pix = QPixmap(self.fscaleOverlay.width(), self.fscaleOverlay.height())
            pix.fill(Qt.transparent)
            now = datetime.datetime.now()
            painter = QPainter(pix)
            painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform, True)
            self.SetDrawPen(painter, linewidth, QColor(0, 0, 0, 160), True)
            painter.drawRect(0, self.camView.height() - labelHeight, self.camView.width(), labelHeight)
            self.SetDrawPen(painter, linewidth, scaleColor, False)
            painter.drawLine(QPoint(posI, bottom), QPoint(posF, bottom))
            painter.drawLine(QPoint(posI, bottom - midtickh1), QPoint(posI, bottom + midtickh1))
            painter.drawLine(QPoint(posF, bottom - midtickh1), QPoint(posF, bottom + midtickh1))
            painter.drawLine(QPoint(posmidtick, bottom - midtickh1), QPoint(posmidtick, bottom + midtickh1))
            painter.drawLine(QPoint(posquartertick1, bottom - midtickh2), QPoint(posquartertick1, bottom + midtickh2))
            painter.drawLine(QPoint(posquartertick2, bottom - midtickh2), QPoint(posquartertick2, bottom + midtickh2))
            painter.setFont(QFont("Sans", pointSize=int(1.5*midtickh1)))
            rect = QRectF(0, bottom - 4*midtickh1, self.camView.width(), midtickh1*3)
            rect2 = QRectF(0, bottom - 1*midtickh1, self.camView.width(), midtickh1*3)
            painter.drawText(rect, str(micronScale) + " " + u"\u03BC" + "m", QTextOption(Qt.AlignHCenter))
            painter.drawText(rect2, " LCO", QTextOption(Qt.AlignLeft))
            painter.drawText(rect2, str(now.year) + "-" + str(now.month) + "-" + str(now.day) + " ", QTextOption(Qt.AlignRight))
            painter.end()
            self.fscaleOverlay.setPixmap(pix)
        else:
            pix = QPixmap(self.fscaleOverlay.width(), self.fscaleOverlay.height())
            pix.fill(Qt.transparent)
            self.fscaleOverlay.setPixmap(pix)
コード例 #11
0
 def paintEvent(self, e):
     painter = QPainter(self)
     if self._size_grip.isVisible():
         painter.save()
         painter.setPen(QColor('white'))
         option = QTextOption()
         option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
         rect = QRect(self._size_grip.pos(), self._size_grip.size())
         painter.drawText(QRectF(rect), '●', option)
         painter.restore()
コード例 #12
0
 def paintEvent(self, e):
     painter = QPainter(self)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(Qt.NoPen)
     painter.setBrush(self.palette().color(QPalette.Window))
     painter.drawRoundedRect(self.rect(), self._border_radius, self._border_radius)
     painter.save()
     painter.setPen(QColor('white'))
     option = QTextOption()
     option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     rect = QRect(self.mapToParent(self._size_grip.pos()), self._size_grip.size())
     painter.drawText(QRectF(rect), '●', option)
     painter.restore()
コード例 #13
0
 def fontValuePixmap(font):
     f = QFont(font)
     img = QImage(16, 16, QImage.Format_ARGB32_Premultiplied)
     img.fill(0)
     p = QPainter(img)
     p.setRenderHint(QPainter.TextAntialiasing, True)
     p.setRenderHint(QPainter.Antialiasing, True)
     f.setPointSize(13)
     p.setFont(f)
     t = QTextOption()
     t.setAlignment(Qt.AlignCenter)
     p.drawText(QRectF(0, 0, 16, 16), 'A', t)
     p.end()
     return QPixmap.fromImage(img)
コード例 #14
0
 def fontValuePixmap(font):
     f = QFont(font)
     img = QImage(16, 16, QImage.Format_ARGB32_Premultiplied)
     img.fill(0)
     p = QPainter(img)
     p.setRenderHint(QPainter.TextAntialiasing, True)
     p.setRenderHint(QPainter.Antialiasing, True)
     f.setPointSize(13)
     p.setFont(f)
     t = QTextOption()
     t.setAlignment(Qt.AlignCenter)
     p.drawText(QRectF(0, 0, 16, 16), 'A', t)
     p.end()
     return QPixmap.fromImage(img)
コード例 #15
0
    def _get_textdoc(self, index):
        """Create the QTextDocument of an item.

        Args:
            index: The QModelIndex of the item to draw.
        """
        # FIXME we probably should do eliding here. See
        # qcommonstyle.cpp:viewItemDrawText
        # https://github.com/qutebrowser/qutebrowser/issues/118
        text_option = QTextOption()
        if self._opt.features & QStyleOptionViewItem.WrapText:
            text_option.setWrapMode(QTextOption.WordWrap)
        else:
            text_option.setWrapMode(QTextOption.ManualWrap)
        text_option.setTextDirection(self._opt.direction)
        text_option.setAlignment(QStyle.visualAlignment(
            self._opt.direction, self._opt.displayAlignment))

        if self._doc is not None:
            self._doc.deleteLater()
        self._doc = QTextDocument(self)
        self._doc.setDefaultFont(self._opt.font)
        self._doc.setDefaultTextOption(text_option)
        self._doc.setDocumentMargin(2)

        stylesheet = """
            .highlight {
                color: {{ conf.colors.completion.match.fg }};
            }
        """
        with jinja.environment.no_autoescape():
            template = jinja.environment.from_string(stylesheet)
        self._doc.setDefaultStyleSheet(template.render(conf=config.val))

        if index.parent().isValid():
            view = self.parent()
            pattern = view.pattern
            columns_to_filter = index.model().columns_to_filter(index)
            if index.column() in columns_to_filter and pattern:
                repl = r'<span class="highlight">\g<0></span>'
                text = re.sub(re.escape(pattern).replace(r'\ ', r'|'),
                              repl, self._opt.text, flags=re.IGNORECASE)
                self._doc.setHtml(text)
            else:
                self._doc.setPlainText(self._opt.text)
        else:
            self._doc.setHtml(
                '<span style="font: {};">{}</span>'.format(
                    html.escape(config.val.fonts.completion.category),
                    html.escape(self._opt.text)))
コード例 #16
0
    def paint(self, painter, option, index):
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        rect = option.rect
        text_rect_height = TextHeight
        cover_spacing = 0
        text_y = rect.y() + rect.height() - text_rect_height
        cover_height = rect.height() - text_rect_height
        cover_width = rect.width() - cover_spacing
        cover_x = rect.x() + cover_spacing // 2
        cover_y = rect.y()
        text_rect = QRectF(rect.x(), text_y, rect.width(), text_rect_height)
        obj = index.data(Qt.DecorationRole)
        if obj is None:
            painter.restore()
            return

        text_color = option.palette.color(QPalette.Text)
        if text_color.lightness() > 150:
            non_text_color = text_color.darker(140)
        else:
            non_text_color = text_color.lighter(150)
        non_text_color.setAlpha(100)
        painter.save()
        pen = painter.pen()
        pen.setColor(non_text_color)
        painter.setPen(pen)
        painter.translate(cover_x, cover_y)
        cover_rect = QRect(0, 0, cover_width, cover_height)
        if isinstance(obj, QColor):
            color = obj
            brush = QBrush(color)
            painter.setBrush(brush)
        else:
            pixmap = obj.scaledToWidth(cover_width, Qt.SmoothTransformation)
            brush = QBrush(pixmap)
            painter.setBrush(brush)
        painter.drawRoundedRect(cover_rect, 3, 3)
        painter.restore()
        option = QTextOption()
        option.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        album_name = index.data(Qt.DisplayRole)
        fm = QFontMetrics(painter.font())
        elided_album_name = fm.elidedText(album_name, Qt.ElideRight,
                                          text_rect.width())
        painter.drawText(text_rect, elided_album_name, option)
        painter.restore()
コード例 #17
0
    def __init__(self, theme):
        QWidget.__init__(self)
        self.theme = theme
        self.themename = theme.name
        self.setMaximumWidth(400)
        picurl = ":/images/theme.png"
        self.url = theme.sample_url
        if theme.sample_pic:
            picurl = theme.sample_pic
        pic = FlatButton(picurl, picurl)
        map = QPixmap(400, 200)
        p = QPainter(map)
        p.setRenderHint(QPainter.Antialiasing)
        p.setRenderHint(QPainter.TextAntialiasing)
        p.drawImage(QRect(0, 0, 400, 200), QImage(picurl))
        p.fillRect(0, 0,
                   map.size().width(),
                   map.size().height(), QColor(69, 187, 230, 125))
        if self.url:
            w = 100
            h = 30

            p.fillRect(QRect((400 - w) / 2, (200 - h) / 2, w, h),
                       QColor(69, 187, 230, 255))
            p.drawRoundedRect(QRect((400 - w) / 2, (200 - h) / 2, w, h), 5, 5)
            font = QFont()
            font.setFamily("Arial")
            font.setBold(True)
            font.setPixelSize(20)
            p.setFont(font)
            p.setPen(QPen(Qt.black))
            p.drawText(QRectF(0, 0, 400, 200), "PREVIEW",
                       QTextOption(Qt.AlignHCenter | Qt.AlignVCenter))

            pic.clicked.connect(self.clicked)
        else:
            pic.setCursor(Qt.ArrowCursor)
        del p

        pic.setHoverPixmap(map)
        pic.setMaximumSize(400, 200)
        pic.setScaledContents(True)
        if theme.aktiv:
            name = QLabel(theme.name.upper() + " (Aktiv)")
        else:
            name = QLabel(theme.name.upper())
        fnt = name.font()
        fnt.setPointSize(13)
        fnt.setBold(True)
        name.setFont(fnt)
        layout = QGridLayout()
        layout.addWidget(pic, 0, 0, 1, 2)
        layout.addWidget(name, 1, 0)
        if not theme.aktiv:
            activate = QPushButton("Activate")
            layout.addWidget(activate, 1, 1, 1, 1, Qt.AlignRight)
            activate.clicked.connect(self.activate)

        self.setLayout(layout)
コード例 #18
0
ファイル: Square.py プロジェクト: rugewit/puzzle
 def paint(self, painter, option, widget):
     super().paint(painter, option, widget)
     painter.setFont(QFont("Roboto", 30))
     painter.fillRect(
         QRectF(1, 1, settings.XYSIDE - 1, settings.XYSIDE - 1),
         QColor("grey"))
     painter.drawText(
         QRectF(1, 1, settings.XYSIDE - 1, settings.XYSIDE - 1),
         str(self.number), QTextOption(Qt.AlignmentFlag.AlignCenter))
コード例 #19
0
    def _get_textdoc(self, index):
        """Create the QTextDocument of an item.

        Args:
            index: The QModelIndex of the item to draw.
        """
        if self._opt is None:
            raise AssertionError
        # FIXME we probably should do eliding here. See
        # qcommonstyle.cpp:viewItemDrawText
        # https://github.com/qutebrowser/qutebrowser/issues/118
        text_option = QTextOption()
        if self._opt.features & QStyleOptionViewItem.WrapText:
            text_option.setWrapMode(QTextOption.WordWrap)
        else:
            text_option.setWrapMode(QTextOption.ManualWrap)
        text_option.setTextDirection(self._opt.direction)
        text_option.setAlignment(
            QStyle.visualAlignment(self._opt.direction,
                                   self._opt.displayAlignment))

        if self._doc is not None:
            self._doc.deleteLater()
        self._doc = QTextDocument(self)
        self._doc.setDefaultFont(self._opt.font)
        self._doc.setDefaultTextOption(text_option)
        self._doc.setDocumentMargin(2)

        if index.parent().isValid():
            view = self.parent()
            pattern = view.pattern
            columns_to_filter = index.model().columns_to_filter(index)
            if index.column() in columns_to_filter and pattern:
                pat = re.escape(pattern).replace(r'\ ', r'|')
                if self._opt.state & QStyle.State_Selected:
                    color = config.val.colors.completion.item.selected.match.fg
                else:
                    color = config.val.colors.completion.match.fg
                _Highlighter(self._doc, pat, color)
            self._doc.setPlainText(self._opt.text)
        else:
            self._doc.setHtml('<span style="font: {};">{}</span>'.format(
                html.escape(config.val.fonts.completion.category),
                html.escape(self._opt.text)))
コード例 #20
0
    def _get_textdoc(self, index):
        """Create the QTextDocument of an item.

        Args:
            index: The QModelIndex of the item to draw.
        """
        # FIXME we probably should do eliding here. See
        # qcommonstyle.cpp:viewItemDrawText
        # https://github.com/The-Compiler/qutebrowser/issues/118
        text_option = QTextOption()
        if self._opt.features & QStyleOptionViewItem.WrapText:
            text_option.setWrapMode(QTextOption.WordWrap)
        else:
            text_option.setWrapMode(QTextOption.ManualWrap)
        text_option.setTextDirection(self._opt.direction)
        text_option.setAlignment(
            QStyle.visualAlignment(self._opt.direction,
                                   self._opt.displayAlignment))

        self._doc = QTextDocument(self)
        self._doc.setDefaultFont(self._opt.font)
        self._doc.setDefaultTextOption(text_option)
        self._doc.setDefaultStyleSheet(
            style.get_stylesheet("""
            .highlight {
                color: {{ color['completion.match.fg'] }};
            }
        """))
        self._doc.setDocumentMargin(2)

        if index.parent().isValid():
            pattern = index.model().pattern
            columns_to_filter = index.model().srcmodel.columns_to_filter
            if index.column() in columns_to_filter and pattern:
                repl = r'<span class="highlight">\g<0></span>'
                text = re.sub(re.escape(pattern),
                              repl,
                              self._opt.text,
                              flags=re.IGNORECASE)
                self._doc.setHtml(text)
            else:
                self._doc.setPlainText(self._opt.text)
        else:
            self._doc.setHtml('<b>{}</b>'.format(html.escape(self._opt.text)))
コード例 #21
0
 def sizeHint(self, option, index):
     msg = index.model().data(index, Qt.DisplayRole)
     field = QRect(option.rect)
     field.setWidth(variables.window_width - variables.WINDOW_PADDING)
     field = field.marginsRemoved(variables.TEXT_PADDING)
     doc = QTextDocument(msg.text)
     doc.setDocumentMargin(0)
     opt = QTextOption()
     opt.setWrapMode(opt.WrapAtWordBoundaryOrAnywhere)
     doc.setDefaultTextOption(opt)
     doc.setDefaultFont(variables.font)
     if msg.user == variables.USER_ME:
         doc.setTextWidth(field.size().width() - 20 - 50)
     else:
         doc.setTextWidth(field.size().width() - 20)
     field.setHeight(int(doc.size().height()))
     field.setWidth(int(doc.idealWidth()))
     field = field.marginsAdded(variables.TEXT_PADDING)
     return QSize(0, field.size().height())
コード例 #22
0
    def paintEvent(self, e):
        width = height = 18
        painter = QPainter(self)
        painter.save()
        painter.setRenderHints(QPainter.Antialiasing)
        painter.translate((self.width() - width) // 2,
                          (self.height() - height) // 2)

        line_height = 1.3
        line_margin = (height - 3 * line_height) / 3
        h1 = line_margin
        h2 = h1 + line_margin + line_height
        h3 = h2 + line_margin + line_height

        pen = painter.pen()
        pen.setColor(QColor("#6F6F6F"))
        pen.setWidthF(line_height)
        painter.setPen(pen)
        painter.setBrush(pen.color())

        # Draw triangle and first line
        triangle_side_length_half = line_margin * 0.6
        triangle_height = triangle_side_length_half * 1.7
        triangle = QPolygonF([
            QPointF(0, h1 - triangle_side_length_half),
            QPointF(triangle_height, h1),
            QPointF(0, h1 + triangle_side_length_half)
        ])
        painter.drawPolygon(triangle)
        painter.drawLine(
            QPointF(triangle_height + triangle_side_length_half, h1),
            QPointF(width, h1))

        # Draw second line
        painter.drawLine(QPointF(0, h2), QPointF(width, h2))

        # Draw third line, show FM text if needed
        if self._app.playlist.mode is PlaylistMode.fm:
            painter.drawLine(QPointF(0, h3), QPointF(width // 2, h3))
            painter.pen()
            pen.setColor(QColor(SOLARIZED_COLORS['blue']))
            painter.setPen(pen)
            font = painter.font()
            rect_h_half = line_margin // 2
            font.setPixelSize(int(rect_h_half * 2))
            painter.setFont(font)
            rect = QRectF(width // 2 + rect_h_half, h3 - rect_h_half,
                          width // 2 - rect_h_half, rect_h_half * 2)
            painter.drawText(rect, "FM", QTextOption(Qt.AlignCenter))
        else:
            painter.drawLine(QPointF(0, h3), QPointF(width, h3))

        painter.restore()
コード例 #23
0
    def paint_detail_view(self, painter: QPainter) -> None:
        self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(),
                                    self.tile_rect.height())

        self.paint_thumbnail(painter)

        lst = (
            [self.fileinfo.basename(),
             bytefmt.humanize(self.fileinfo.size())] + list(self.make_text()))

        text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter)
        text_option.setWrapMode(QTextOption.NoWrap)

        total_width = self.tile_rect.width() - self.thumbnail_rect.width() - 8

        widths = [60, 10, 10, 10, 10, 10]
        x = self.thumbnail_rect.width() + 4
        for idx, text in enumerate(lst[:-1]):
            if idx != 0:
                text_option.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

            width = total_width * (widths[idx] / 100)
            painter.drawText(QRectF(x, 0, width, self.tile_rect.height()),
                             text, text_option)
            x += width
コード例 #24
0
    def _get_textdoc(self, index):
        """Create the QTextDocument of an item.

        Args:
            index: The QModelIndex of the item to draw.
        """
        # FIXME we probably should do eliding here. See
        # qcommonstyle.cpp:viewItemDrawText
        text_option = QTextOption()
        if self._opt.features & QStyleOptionViewItem.WrapText:
            text_option.setWrapMode(QTextOption.WordWrap)
        else:
            text_option.setWrapMode(QTextOption.ManualWrap)
        text_option.setTextDirection(self._opt.direction)
        text_option.setAlignment(QStyle.visualAlignment(
            self._opt.direction, self._opt.displayAlignment))

        self._doc = QTextDocument(self)
        if index.parent().isValid():
            self._doc.setPlainText(self._opt.text)
        else:
            self._doc.setHtml('<b>{}</b>'.format(html.escape(self._opt.text)))
        self._doc.setDefaultFont(self._opt.font)
        self._doc.setDefaultTextOption(text_option)
        self._doc.setDefaultStyleSheet(style.get_stylesheet("""
            .highlight {
                {{ color['completion.match.fg'] }}
            }
        """))
        self._doc.setDocumentMargin(2)

        if index.column() == 0:
            marks = index.data(basecompletion.Role.marks)
            if marks is None:
                return
            for mark in marks:
                cur = QTextCursor(self._doc)
                cur.setPosition(mark[0])
                cur.setPosition(mark[1], QTextCursor.KeepAnchor)
                txt = cur.selectedText()
                cur.removeSelectedText()
                cur.insertHtml('<span class="highlight">{}</span>'.format(
                    html.escape(txt)))
コード例 #25
0
    def __init__(self, parent):
        super().__init__(parent)
        self.uas = None
        svgRenderer = QSvgRenderer('res/barometer.svg')

        bkgnd = QGraphicsSvgItem()
        bkgnd.setSharedRenderer(svgRenderer)
        bkgnd.setCacheMode(QGraphicsItem.NoCache)
        bkgnd.setElementId('background')

        scene = QGraphicsScene()
        scene.addItem(bkgnd)
        scene.setSceneRect(bkgnd.boundingRect())

        self.needle = QGraphicsSvgItem()
        self.needle.setSharedRenderer(svgRenderer)
        self.needle.setCacheMode(QGraphicsItem.NoCache)
        self.needle.setElementId('needle')
        self.needle.setParentItem(bkgnd)
        self.needle.setPos(
            bkgnd.boundingRect().width() / 2 -
            self.needle.boundingRect().width() / 2,
            bkgnd.boundingRect().height() / 2 -
            self.needle.boundingRect().height() / 2)
        self.needle.setTransformOriginPoint(
            self.needle.boundingRect().width() / 2,
            self.needle.boundingRect().height() / 2)
        # textElement = svgRenderer.boundsOnElement('needle-text')
        self.digitalBaro = QGraphicsTextItem()
        self.digitalBaro.setDefaultTextColor(QColor(255, 255, 255))
        self.digitalBaro.document().setDefaultTextOption(
            QTextOption(Qt.AlignCenter))
        self.digitalBaro.setFont(QFont('monospace', 13, 60))
        self.digitalBaro.setParentItem(bkgnd)

        txm = QTransform()
        txm.translate(
            bkgnd.boundingRect().center().x(),
            bkgnd.boundingRect().height() -
            1.5 * self.digitalBaro.document().size().height())
        self.digitalBaro.setTransform(txm, False)

        view = QGraphicsView(scene)
        view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        layout = QVBoxLayout()
        layout.addWidget(view)
        self.setLayout(layout)
        self.setBarometer(1000)
コード例 #26
0
    def _get_textdoc(self, index):
        """Create the QTextDocument of an item.

        Args:
            index: The QModelIndex of the item to draw.
        """
        # FIXME we probably should do eliding here. See
        # qcommonstyle.cpp:viewItemDrawText
        # https://github.com/qutebrowser/qutebrowser/issues/118
        text_option = QTextOption()
        if self._opt.features & QStyleOptionViewItem.WrapText:
            text_option.setWrapMode(QTextOption.WordWrap)
        else:
            text_option.setWrapMode(QTextOption.ManualWrap)
        text_option.setTextDirection(self._opt.direction)
        text_option.setAlignment(QStyle.visualAlignment(
            self._opt.direction, self._opt.displayAlignment))

        if self._doc is not None:
            self._doc.deleteLater()
        self._doc = QTextDocument(self)
        self._doc.setDefaultFont(self._opt.font)
        self._doc.setDefaultTextOption(text_option)
        self._doc.setDocumentMargin(2)

        if index.parent().isValid():
            view = self.parent()
            pattern = view.pattern
            columns_to_filter = index.model().columns_to_filter(index)
            if index.column() in columns_to_filter and pattern:
                pat = re.escape(pattern).replace(r'\ ', r'|')
                if self._opt.state & QStyle.State_Selected:
                    color = config.val.colors.completion.item.selected.match.fg
                else:
                    color = config.val.colors.completion.match.fg
                _Highlighter(self._doc, pat, color)
            self._doc.setPlainText(self._opt.text)
        else:
            self._doc.setHtml(
                '<span style="font: {};">{}</span>'.format(
                    html.escape(config.val.fonts.completion.category),
                    html.escape(self._opt.text)))
コード例 #27
0
    def _get_textdoc(self, index):
        """Create the QTextDocument of an item.

        Args:
            index: The QModelIndex of the item to draw.
        """
        # FIXME we probably should do eliding here. See
        # qcommonstyle.cpp:viewItemDrawText
        # https://github.com/The-Compiler/qutebrowser/issues/118
        text_option = QTextOption()
        if self._opt.features & QStyleOptionViewItem.WrapText:
            text_option.setWrapMode(QTextOption.WordWrap)
        else:
            text_option.setWrapMode(QTextOption.ManualWrap)
        text_option.setTextDirection(self._opt.direction)
        text_option.setAlignment(QStyle.visualAlignment(
            self._opt.direction, self._opt.displayAlignment))

        if self._doc is not None:
            self._doc.deleteLater()
        self._doc = QTextDocument(self)
        self._doc.setDefaultFont(self._opt.font)
        self._doc.setDefaultTextOption(text_option)
        self._doc.setDefaultStyleSheet(style.get_stylesheet("""
            .highlight {
                color: {{ color['completion.match.fg'] }};
            }
        """))
        self._doc.setDocumentMargin(2)

        if index.parent().isValid():
            pattern = index.model().pattern
            columns_to_filter = index.model().srcmodel.columns_to_filter
            if index.column() in columns_to_filter and pattern:
                repl = r'<span class="highlight">\g<0></span>'
                text = re.sub(re.escape(pattern).replace(r'\ ', r'.*'),
                              repl, self._opt.text, flags=re.IGNORECASE)
                self._doc.setHtml(text)
            else:
                self._doc.setPlainText(self._opt.text)
        else:
            self._doc.setHtml('<b>{}</b>'.format(html.escape(self._opt.text)))
コード例 #28
0
 def toggleNonprintable(self):
     if self.actionsSelector.nonprintableAction.isChecked():
         option = QTextOption()
         option.setFlags(QTextOption.ShowTabsAndSpaces
                         | QTextOption.ShowLineAndParagraphSeparators)
         self.editView.document().setDefaultTextOption(option)
     else:
         option = QTextOption()
         self.editView.document().setDefaultTextOption(option)
コード例 #29
0
ファイル: docviewer.py プロジェクト: johnblommers/novelWriter
    def __init__(self, theParent, theProject):
        QTextBrowser.__init__(self)

        logger.debug("Initialising DocViewer ...")

        # Class Variables
        self.mainConf = nw.CONFIG
        self.theProject = theProject
        self.theParent = theParent
        self.theTheme = theParent.theTheme
        self.theHandle = None

        self.qDocument = self.document()
        self.setMinimumWidth(300)
        self.initViewer()

        theOpt = QTextOption()
        if self.mainConf.doJustify:
            theOpt.setAlignment(Qt.AlignJustify)
        self.qDocument.setDefaultTextOption(theOpt)

        logger.debug("DocViewer initialisation complete")

        return
コード例 #30
0
ファイル: customWidget.py プロジェクト: wqslucifer/MLTools
    def doDrag(self):
        drag = QDrag(self)
        mimeData = QMimeData()
        mimeData.setText(self.dragText)
        drag.setMimeData(mimeData)

        drag_img = QPixmap(self.width(), self.itemRowHeight)
        drag_img.fill(QColor(255, 255, 255, 100))
        painter = QPainter(drag_img)
        painter.setPen(QColor(0, 0, 0, 200))
        painter.drawText(QRectF(40, 0, self.width(), self.itemRowHeight),
                         self.dragText, QTextOption(Qt.AlignVCenter))
        painter.end()

        drag.setPixmap(drag_img)
        drag.setHotSpot(self.dragPointAtItem)
        if drag.exec(Qt.MoveAction) == Qt.MoveAction:
            print('drag')
コード例 #31
0
ファイル: textwidget.py プロジェクト: correosdelbosque/lector
 def togglewhiteSpace(self, state=True):
     """
     Show or hide whitespace and line ending markers
     """
     option = QTextOption()
     if state:
         option.setFlags(QTextOption.ShowTabsAndSpaces |
                         QTextOption.ShowLineAndParagraphSeparators)
     else:
         option.setFlags(option.flags() & ~option.ShowTabsAndSpaces &
                         ~option.ShowLineAndParagraphSeparators)
     self.document().setDefaultTextOption(option)
     settings.set('editor:whiteSpace', state)
コード例 #32
0
    def drawStatus(self, painter):
        if not self.text():
            return

        painter.save()
        font = self.font()
        font.setPixelSize(self._status_font_size)
        painter.setFont(font)
        pen = painter.pen()
        border_color = self.palette().color(QPalette.Window)
        pen.setColor(QColor(border_color))
        painter.setPen(pen)
        w = h = self._width // 2 - 2
        painter.translate(self._width - w, self._width - h)
        text_rect = QRectF(0, 0, w, h)
        text_bg_color = QColor(COLORS[self._status_color])
        text_bg_color.setAlpha(225)
        painter.setBrush(text_bg_color)
        radius = 4
        painter.drawRoundedRect(text_rect, radius, radius)
        painter.drawText(text_rect, self.text(), QTextOption(Qt.AlignCenter))
        painter.restore()
コード例 #33
0
ファイル: tip_info_dialog.py プロジェクト: 2bds/quantx
 def InitUserInterface(self):
     win_size_x = 395
     win_size_y = 90 # 两行文字,110 三行文字
     self.resize(win_size_x, win_size_y)
     self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool)
     
     self.widget = QWidget()
     self.widget.setGeometry(QRect(0, 0, win_size_x, win_size_y))
     
     self.text_edit = QTextEdit()
     self.text_edit.setFont(QFont("SimSun", 10))
     self.text_edit.setReadOnly(True)
     self.text_edit.setLineWrapMode(QTextEdit.WidgetWidth)
     self.text_edit.document().setDefaultTextOption(QTextOption(Qt.AlignCenter))
     
     self.button_box = QDialogButtonBox(self.widget)
     self.button_box.setStandardButtons(QDialogButtonBox.Ok)
     self.button_box.button(QDialogButtonBox.Ok).setText("已  阅")
     self.button_box.setCenterButtons(True)
     self.button_box.accepted.connect(self.OnButtonClose)
     
     self.v_box = QVBoxLayout()
     self.v_box.setContentsMargins(5, 5, 5, 5)
     self.spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
     self.v_box.addWidget(self.text_edit)
     self.v_box.addItem(self.spacer)
     self.v_box.addWidget(self.button_box)
     self.setLayout(self.v_box)
     
     self.timer_show = QTimer()
     self.timer_stay = QTimer()
     self.timer_hide = QTimer()
     
     self.timer_show.timeout.connect(self.OnTimerShow)
     self.timer_stay.timeout.connect(self.OnTimerStay)
     self.timer_hide.timeout.connect(self.OnTimerHide)
     
     pub.subscribe(self.OnTipInfoMessage, "tip.info.message")
コード例 #34
0
ファイル: doceditor.py プロジェクト: johnblommers/novelWriter
    def initEditor(self):
        """Initialise or re-initialise the editor with the user's settings.
        This function is both called when the editor is created, and when the user changes the
        main editor preferences.
        """

        # Reload dictionaries
        self.setDictionaries()

        # Set Font
        theFont = QFont()
        if self.mainConf.textFont is None:
            # If none is defined, set the default back to config
            self.mainConf.textFont = self.qDocument.defaultFont().family()
        theFont.setFamily(self.mainConf.textFont)
        theFont.setPointSize(self.mainConf.textSize)
        self.setFont(theFont)

        docPalette = self.palette()
        docPalette.setColor(QPalette.Base, QColor(*self.theTheme.colBack))
        docPalette.setColor(QPalette.Text, QColor(*self.theTheme.colText))
        self.setPalette(docPalette)

        # Set default text margins
        self.qDocument.setDocumentMargin(self.mainConf.textMargin)

        # Also set the document text options for the document text flow
        theOpt = QTextOption()
        if self.mainConf.tabWidth is not None:
            if self.mainConf.verQtValue >= 51000:
                theOpt.setTabStopDistance(self.mainConf.tabWidth)
        if self.mainConf.doJustify:
            theOpt.setAlignment(Qt.AlignJustify)
        self.qDocument.setDefaultTextOption(theOpt)

        self.hLight.initHighlighter()

        # If we have a document open, we should reload it in case the font changed
        if self.theHandle is not None:
            tHandle = self.theHandle
            self.clearEditor()
            self.loadText(tHandle)
            self.changeWidth()

        return True
コード例 #35
0
ファイル: gallery.py プロジェクト: darmstard/happypanda
	def text_layout(self, text, width, font, font_metrics):
		"Lays out wrapped text"
		text_option = QTextOption(Qt.AlignCenter)
		text_option.setUseDesignMetrics(True)
		text_option.setWrapMode(QTextOption.WordWrap)
		layout = QTextLayout(text, font)
		layout.setTextOption(text_option)
		leading = font_metrics.leading()
		height = 0
		layout.setCacheEnabled(True)
		layout.beginLayout()
		while True:
			line = layout.createLine()
			if not line.isValid():
				break
			line.setLineWidth(width)
			height += leading
			line.setPosition(QPointF(0, height))
			height += line.height()
		layout.endLayout()
		return layout
コード例 #36
0
    def paintEvent(self, event):
        painter = QPainter(self.viewport())
        painter.fillRect(0, 0, self.viewport().width(), self.viewport().height(), QColor('#181818'))

        self.pos = self.verticalScrollBar().value()
        data_start = 0
        data_end = 0

        if len(self.data) > self.visible_lines():
            data_start = self.pos
            data_end = self.pos + self.visible_lines()
        else:
            data_end = len(self.data)

        drawing_pos_y = 10
        trace_depth = 0

        fontMetrics = QFontMetrics(QFont(self.font))
        text_options = QTextOption()
        text_options.setAlignment(Qt.AlignLeft)
        text_options.setWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)

        for i, line in enumerate(self.data):
            if i == self.pos:
                break
            if line['event'] == 'leave':
                trace_depth -= 1
            elif line['event'] == 'enter':
                trace_depth += 1

        for i, line in enumerate(self.data[data_start:data_end]):
            if i > self.visible_lines():
                break

            is_obj = False
            if isinstance(line['data'], str) and line['data'].startswith('{'):
                is_obj = True
                line['data'] = json.loads(line['data'])

            drawing_pos_x = 10
            painter.setPen(QColor('#fff'))

            if line['event'] == 'leave':
                if trace_depth:
                    trace_depth -= 1
                drawing_pos_x += (trace_depth * 20)
                painter.setPen(QColor('crimson'))
                painter.setBrush(QColor('#222'))
                polygon = QPolygon()
                polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5)))
                painter.drawPolygon(polygon)
            elif line['event'] == 'enter':
                trace_depth += 1
                drawing_pos_x += (trace_depth * 20)
                painter.setPen(QColor('yellowgreen'))
                painter.setBrush(QColor('#222'))
                polygon = QPolygon()
                polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(int(floor(self.viewport().width())) - 5, drawing_pos_y + (self._char_height * 0.5)))
                polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                #polygon.append(QPoint(drawing_pos_x + 21, drawing_pos_y + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5)))
                painter.drawPolygon(polygon)

            drawing_pos_x += 20
            rect = QRectF(drawing_pos_x, drawing_pos_y, self.viewport().width() - 25 - drawing_pos_x, self._char_height + 10)

            if line['event'] == 'enter':
                arg_str = '('
                for a in range(len(line['data'])):
                    arg_str += 'arg_{0}, '.format(a)

                if len(line['data']):
                    arg_str = arg_str[:-2]
                arg_str += ')'
                painter.drawText(rect, line['class'] + arg_str, option=text_options)
            else:
                painter.drawText(rect, line['class'], option=text_options)

            drawing_pos_y += self._char_height + 15

            if isinstance(line['data'], str):
                if line['data']:
                    rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, self.viewport().width() - drawing_pos_x - 25, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, line['data'])
                    rect = QRectF(drawing_pos_x, drawing_pos_y, rect.width(), rect.height())
                    painter.setPen(QColor('#888'))
                    painter.drawText(rect, line['data'], option=text_options)
                    drawing_pos_y += rect.height() + 5
            else:
                width = int(floor(self.viewport().width() - drawing_pos_x - (5 * self._char_width) - 35))
                max_chars = int(floor(width / self._char_width))
                hold_x = drawing_pos_x + 5
                width -= 20
                painter.setPen(QColor('#888'))
                for data in line['data']:
                    drawing_pos_x = hold_x
                    if isinstance(line['data'][data], int):
                        text = '{0:d}'.format(line['data'][data])
                    elif isinstance(line['data'][data], str):
                        text = line['data'][data]
                    elif isinstance(line['data'][data], list):
                        text = str(line['data'][data])
                    else:
                        text = str(line['data'][data])

                    if line['event'] == 'enter':
                        arg = 'arg_{0}: '.format(data)
                        painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, arg)
                        drawing_pos_x += len(arg) * self._char_width
                    elif line['event'] == 'leave':
                        retval = data + ': '
                        painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, retval)
                        drawing_pos_x += len(retval) * self._char_width

                    if len(text) * self._char_width < width:
                        painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, text)
                        drawing_pos_y += self._char_height + 5
                    else:
                        rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, width, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, text)
                        rect = QRectF(rect)
                        painter.drawText(rect, text, option=text_options)
                        drawing_pos_y += rect.height() + 5

            drawing_pos_y += self._char_height + 5
コード例 #37
0
    def paint(self, painter, option, index):
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        rect = option.rect
        text_rect_height = 30
        img_text_height = self.view.img_text_height
        source_rect_height = img_text_height - text_rect_height
        text_y = rect.y() + rect.height() - img_text_height
        cover_height = rect.height() - img_text_height
        cover_width = rect.width()
        text_rect = QRectF(rect.x(), text_y, rect.width(), text_rect_height)
        source_rect = QRectF(rect.x(), text_y + text_rect_height - 5,
                             rect.width(), source_rect_height + 5)
        obj = index.data(Qt.DecorationRole)
        if obj is None:
            painter.restore()
            return

        text_color = option.palette.color(QPalette.Text)
        if text_color.lightness() > 150:
            non_text_color = text_color.darker(140)
        else:
            non_text_color = text_color.lighter(150)
        non_text_color.setAlpha(100)
        painter.save()
        pen = painter.pen()
        pen.setColor(non_text_color)
        painter.setPen(pen)
        painter.translate(rect.x(), rect.y())
        if isinstance(obj, QColor):
            color = obj
            brush = QBrush(color)
            painter.setBrush(brush)
        else:
            if obj.height() < obj.width():
                pixmap = obj.scaledToHeight(cover_height,
                                            Qt.SmoothTransformation)
            else:
                pixmap = obj.scaledToWidth(cover_width,
                                           Qt.SmoothTransformation)
            brush = QBrush(pixmap)
            painter.setBrush(brush)
        border_radius = 3
        if self.as_circle:
            border_radius = cover_width // 2
        cover_rect = QRect(0, 0, cover_width, cover_height)
        painter.drawRoundedRect(cover_rect, border_radius, border_radius)
        painter.restore()
        option = QTextOption()
        source_option = QTextOption()
        if self.as_circle:
            option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            source_option.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        else:
            option.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            source_option.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        name = index.data(Qt.DisplayRole)
        fm = QFontMetrics(painter.font())
        elided_name = fm.elidedText(name, Qt.ElideRight, text_rect.width())
        source = index.data(Qt.WhatsThisRole)
        painter.drawText(text_rect, elided_name, option)
        painter.restore()
        painter.save()
        pen = painter.pen()
        font = painter.font()
        resize_font(font, -2)
        painter.setFont(font)
        pen.setColor(non_text_color)
        painter.setPen(non_text_color)
        painter.drawText(source_rect, source, source_option)
        painter.restore()
コード例 #38
0
ファイル: file_item_renderer.py プロジェクト: Grumbel/dirtool
    def paint_smallicon_view(self, painter: QPainter) -> None:
        self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(), self.tile_rect.height())

        font = self.style.font
        fm = self.style.fm

        painter.setFont(font)
        self.paint_thumbnail(painter)

        if self.zoom_index in [0, 1]:
            text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter)
            text_option.setWrapMode(QTextOption.NoWrap)
            text_rect = QRect(QPoint(self.tile_rect.height() + 4,
                                     0),
                              QPoint(self.tile_rect.width(),
                                     self.tile_rect.height()))
            text = self.fileinfo.basename()
            text = fm.elidedText(text, Qt.ElideRight, text_rect.width())
            painter.drawText(QRectF(text_rect),
                             text,
                             text_option)
        elif self.zoom_index in [2]:
            text_rect = QRect(QPoint(self.tile_rect.height() + 4,
                                     0),
                              QPoint(self.tile_rect.width() - 80,
                                     self.tile_rect.height()))
            text = self.fileinfo.basename()
            text = fm.elidedText(text, Qt.ElideRight, text_rect.width())
            text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter)
            text_option.setWrapMode(QTextOption.NoWrap)
            painter.drawText(QRectF(text_rect), text, text_option)

            text_rect = QRect(QPoint(self.tile_rect.width() - 80,
                                     0),
                              QPoint(self.tile_rect.width(),
                                     self.tile_rect.height()))
            text = bytefmt.humanize(self.fileinfo.size())
            text = fm.elidedText(text, Qt.ElideRight, text_rect.width())
            text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter)

            text_option.setWrapMode(QTextOption.NoWrap)
            painter.setPen(QColor(96, 96, 96))
            painter.drawText(QRectF(text_rect), text, text_option)
        else:
            top_left_text, top_right_text, bottom_left_text, bottom_right = self.make_text()

            row1_rect = QRect(QPoint(self.tile_rect.left() + self.tile_rect.height() + 8,
                                     self.tile_rect.top()),
                              QPoint(self.tile_rect.right() - 8,
                                     self.tile_rect.top() + self.tile_rect.height() / 2))
            row2_rect = QRect(QPoint(self.tile_rect.left() + self.tile_rect.height() + 8,
                                     self.tile_rect.top() + self.tile_rect.height() / 2),
                              QPoint(self.tile_rect.right() - 8,
                                     self.tile_rect.bottom()))

            # row 1
            text_rect = QRect(QPoint(row1_rect.left(),
                                     row1_rect.top()),
                              QPoint(row1_rect.right() - 80,
                                     row1_rect.bottom()))
            text = self.fileinfo.basename()
            text = fm.elidedText(text, Qt.ElideRight, text_rect.width())
            text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter)
            text_option.setWrapMode(QTextOption.NoWrap)
            painter.drawText(QRectF(text_rect), text, text_option)

            text_rect = QRect(QPoint(row1_rect.left() - 80,
                                     row1_rect.top()),
                              QPoint(row1_rect.right(),
                                     row1_rect.bottom()))
            text = bytefmt.humanize(self.fileinfo.size())
            text = fm.elidedText(text, Qt.ElideRight, text_rect.width())
            text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter)

            text_option.setWrapMode(QTextOption.NoWrap)
            painter.setPen(QColor(96, 96, 96))
            painter.drawText(QRectF(text_rect), text, text_option)

            # row 2
            text_rect = QRect(QPoint(row2_rect.left(),
                                     row2_rect.top()),
                              QPoint(row2_rect.right() - 80,
                                     row2_rect.bottom()))
            text = bottom_left_text
            text = fm.elidedText(text, Qt.ElideRight, text_rect.width())
            text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter)
            text_option.setWrapMode(QTextOption.NoWrap)
            painter.drawText(QRectF(text_rect), text, text_option)

            text_rect = QRect(QPoint(row2_rect.left() - 80,
                                     row2_rect.top()),
                              QPoint(row2_rect.right(),
                                     row2_rect.bottom()))
            text = top_left_text
            text = fm.elidedText(text, Qt.ElideRight, text_rect.width())
            text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter)

            text_option.setWrapMode(QTextOption.NoWrap)
            painter.setPen(QColor(96, 96, 96))
            painter.drawText(QRectF(text_rect), text, text_option)
コード例 #39
0
ファイル: gallery.py プロジェクト: darmstard/happypanda
	def paint(self, painter, option, index):
		assert isinstance(painter, QPainter)
		if index.data(Qt.UserRole+1):
			if app_constants.HIGH_QUALITY_THUMBS:
				painter.setRenderHint(QPainter.SmoothPixmapTransform)
			painter.setRenderHint(QPainter.Antialiasing)
			gallery = index.data(Qt.UserRole+1)
			title = gallery.title
			artist = gallery.artist
			title_color = app_constants.GRID_VIEW_TITLE_COLOR
			artist_color = app_constants.GRID_VIEW_ARTIST_COLOR
			label_color = app_constants.GRID_VIEW_LABEL_COLOR
			# Enable this to see the defining box
			#painter.drawRect(option.rect)
			# define font size
			if 20 > len(title) > 15:
				title_size = "font-size:{}px;".format(self.font_size)
			elif 30 > len(title) > 20:
				title_size = "font-size:{}px;".format(self.font_size-1)
			elif 40 > len(title) >= 30:
				title_size = "font-size:{}px;".format(self.font_size-2)
			elif 50 > len(title) >= 40:
				title_size = "font-size:{}px;".format(self.font_size-3)
			elif len(title) >= 50:
				title_size = "font-size:{}px;".format(self.font_size-4)
			else:
				title_size = "font-size:{}px;".format(self.font_size)

			if 30 > len(artist) > 20:
				artist_size = "font-size:{}px;".format(self.font_size)
			elif 40 > len(artist) >= 30:
				artist_size = "font-size:{}px;".format(self.font_size-1)
			elif len(artist) >= 40:
				artist_size = "font-size:{}px;".format(self.font_size-2)
			else:
				artist_size = "font-size:{}px;".format(self.font_size)

			#painter.setPen(QPen(Qt.NoPen))
			#option.rect = option.rect.adjusted(11, 10, 0, 0)
			option.rect.setWidth(self.W)

			option.rect.setHeight(self.H)
			rec = option.rect.getRect()
			x = rec[0]
			y = rec[1]
			w = rec[2]
			h = rec[3]

			text_area = QTextDocument()
			text_area.setDefaultFont(option.font)
			text_area.setHtml("""
			<head>
			<style>
			#area
			{{
				display:flex;
				width:140px;
				height:10px
			}}
			#title {{
			position:absolute;
			color: {4};
			font-weight:bold;
			{0}
			}}
			#artist {{
			position:absolute;
			color: {5};
			top:20px;
			right:0;
			{1}
			}}
			</style>
			</head>
			<body>
			<div id="area">
			<center>
			<div id="title">{2}
			</div>
			<div id="artist">{3}
			</div>
			</div>
			</center>
			</body>
			""".format(title_size, artist_size, title, artist, title_color, artist_color))
			text_area.setTextWidth(w)

			#chapter_area = QTextDocument()
			#chapter_area.setDefaultFont(option.font)
			#chapter_area.setHtml("""
			#<font color="black">{}</font>
			#""".format("chapter"))
			#chapter_area.setTextWidth(w)
			def center_img(width):
				new_x = x
				if width < w:
					diff = w - width
					offset = diff//2
					new_x += offset
				return new_x
			# if we can't find a cached image
			pix_cache = QPixmapCache.find(self.key(gallery.profile))
			if isinstance(pix_cache, QPixmap):
				self.image = pix_cache
				img_x = center_img(self.image.width())
				if self.image.height() < self.image.width(): #to keep aspect ratio
					painter.drawPixmap(QPoint(img_x,y),
							self.image)
				else:
					painter.drawPixmap(QPoint(img_x,y),
							self.image)
			else:
				self.image = QPixmap(gallery.profile)
				img_x = center_img(self.image.width())
				QPixmapCache.insert(self.key(gallery.profile), self.image)
				if self.image.height() < self.image.width(): #to keep aspect ratio
					painter.drawPixmap(QPoint(img_x,y),
							self.image)
				else:
					painter.drawPixmap(QPoint(img_x,y),
							self.image)

			# draw star if it's favorited
			if gallery.fav == 1:
				painter.drawPixmap(QPointF(x,y), QPixmap(app_constants.STAR_PATH))
			
			if app_constants._REFRESH_EXTERNAL_VIEWER:
				if app_constants.USE_EXTERNAL_VIEWER:
					self.external_icon = self.file_icons.get_external_file_icon()
				else:
					self.external_icon = self.file_icons.get_default_file_icon()
			
			if gallery.state == self.G_DOWNLOAD:
				painter.save()
				dl_box = QRect(x, y, w, 20)
				painter.setBrush(QBrush(QColor(0,0,0,123)))
				painter.setPen(QColor('white'))
				painter.drawRect(dl_box)
				painter.drawText(dl_box, Qt.AlignCenter, 'Downloading...')
				painter.restore()
			else:
				if app_constants.DISPLAY_GALLERY_TYPE:
					self.type_icon = self.file_icons.get_file_icon(gallery.path)
					if self.type_icon and not self.type_icon.isNull():
						self.type_icon.paint(painter, QRect(x+2, y+app_constants.THUMB_H_SIZE-16, 16, 16))

				if app_constants.USE_EXTERNAL_PROG_ICO:
					if self.external_icon and not self.external_icon.isNull():
						self.external_icon.paint(painter, QRect(x+w-30, y+app_constants.THUMB_H_SIZE-28, 28, 28))

			def draw_text_label(lbl_h):
				#draw the label for text
				painter.save()
				painter.translate(x, y+app_constants.THUMB_H_SIZE)
				box_color = QBrush(QColor(label_color))#QColor(0,0,0,123))
				painter.setBrush(box_color)
				rect = QRect(0, 0, w, lbl_h) #x, y, width, height
				painter.fillRect(rect, box_color)
				painter.restore()
				return rect

			if option.state & QStyle.State_MouseOver or\
			    option.state & QStyle.State_Selected:
				title_layout = self.text_layout(title, w, self.title_font, self.title_font_m)
				artist_layout = self.text_layout(artist, w, self.artist_font, self.artist_font_m)
				t_h = title_layout.boundingRect().height()
				a_h = artist_layout.boundingRect().height()

				if app_constants.GALLERY_FONT_ELIDE:
					lbl_rect = draw_text_label(min(t_h+a_h+3, app_constants.GRIDBOX_LBL_H))
				else:
					lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H)

				clipping = QRectF(x, y+app_constants.THUMB_H_SIZE, w, app_constants.GRIDBOX_LBL_H - 10)
				title_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE),
					  clip=clipping)
				artist_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE+t_h),
					   clip=clipping)
				#painter.fillRect(option.rect, QColor)
			else:
				if app_constants.GALLERY_FONT_ELIDE:
					lbl_rect = draw_text_label(self.text_label_h)
				else:
					lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H)
				# draw text
				painter.save()
				alignment = QTextOption(Qt.AlignCenter)
				alignment.setUseDesignMetrics(True)
				title_rect = QRectF(0,0,w, self.title_font_m.height())
				artist_rect = QRectF(0,self.artist_font_m.height(),w,
						 self.artist_font_m.height())
				painter.translate(x, y+app_constants.THUMB_H_SIZE)
				if app_constants.GALLERY_FONT_ELIDE:
					painter.setFont(self.title_font)
					painter.setPen(QColor(title_color))
					painter.drawText(title_rect,
							 self.title_font_m.elidedText(title, Qt.ElideRight, w-10),
							 alignment)
				
					painter.setPen(QColor(artist_color))
					painter.setFont(self.artist_font)
					alignment.setWrapMode(QTextOption.NoWrap)
					painter.drawText(artist_rect,
								self.title_font_m.elidedText(artist, Qt.ElideRight, w-10),
								alignment)
				else:
					text_area.setDefaultFont(QFont(self.font_name))
					text_area.drawContents(painter)
				##painter.resetTransform()
				painter.restore()

			if option.state & QStyle.State_Selected:
				painter.save()
				selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE)
				painter.setPen(Qt.NoPen)
				painter.setBrush(QBrush(QColor(164,164,164,120)))
				p_path = QPainterPath()
				p_path.setFillRule(Qt.WindingFill)
				p_path.addRoundedRect(selected_rect, 5,5)
				p_path.addRect(x,y, 20, 20)
				p_path.addRect(x+w-20,y, 20, 20)
				painter.drawPath(p_path.simplified())
				#painter.fillRect(selected_rect, QColor(164,164,164,120))
				painter.restore()

			#if option.state & QStyle.State_Selected:
			#	painter.setPen(QPen(option.palette.highlightedText().color()))
		else:
			super().paint(painter, option, index)
コード例 #40
0
ファイル: gallery.py プロジェクト: ImoutoChan/happypanda
	def paint(self, painter, option, index):
		assert isinstance(painter, QPainter)
		if index.data(Qt.UserRole+1):
			if app_constants.HIGH_QUALITY_THUMBS:
				painter.setRenderHint(QPainter.SmoothPixmapTransform)
			painter.setRenderHint(QPainter.Antialiasing)
			gallery = index.data(Qt.UserRole+1)
			title = gallery.title
			artist = gallery.artist
			title_color = app_constants.GRID_VIEW_TITLE_COLOR
			artist_color = app_constants.GRID_VIEW_ARTIST_COLOR
			label_color = app_constants.GRID_VIEW_LABEL_COLOR
			# Enable this to see the defining box
			#painter.drawRect(option.rect)
			# define font size
			if 20 > len(title) > 15:
				title_size = "font-size:{}px;".format(self.font_size)
			elif 30 > len(title) > 20:
				title_size = "font-size:{}px;".format(self.font_size-1)
			elif 40 > len(title) >= 30:
				title_size = "font-size:{}px;".format(self.font_size-2)
			elif 50 > len(title) >= 40:
				title_size = "font-size:{}px;".format(self.font_size-3)
			elif len(title) >= 50:
				title_size = "font-size:{}px;".format(self.font_size-4)
			else:
				title_size = "font-size:{}px;".format(self.font_size)

			if 30 > len(artist) > 20:
				artist_size = "font-size:{}px;".format(self.font_size)
			elif 40 > len(artist) >= 30:
				artist_size = "font-size:{}px;".format(self.font_size-1)
			elif len(artist) >= 40:
				artist_size = "font-size:{}px;".format(self.font_size-2)
			else:
				artist_size = "font-size:{}px;".format(self.font_size)

			#painter.setPen(QPen(Qt.NoPen))
			#option.rect = option.rect.adjusted(11, 10, 0, 0)
			option.rect.setWidth(self.W)

			option.rect.setHeight(self.H)
			rec = option.rect.getRect()
			x = rec[0]
			y = rec[1]
			w = rec[2]
			h = rec[3]

			text_area = QTextDocument()
			text_area.setDefaultFont(option.font)
			text_area.setHtml("""
			<head>
			<style>
			#area
			{{
				display:flex;
				width:{6}px;
				height:{7}px
			}}
			#title {{
			position:absolute;
			color: {4};
			font-weight:bold;
			{0}
			}}
			#artist {{
			position:absolute;
			color: {5};
			top:20px;
			right:0;
			{1}
			}}
			</style>
			</head>
			<body>
			<div id="area">
			<center>
			<div id="title">{2}
			</div>
			<div id="artist">{3}
			</div>
			</div>
			</center>
			</body>
			""".format(title_size, artist_size, title, artist, title_color, artist_color,
			  130+app_constants.SIZE_FACTOR, 1+app_constants.SIZE_FACTOR))
			text_area.setTextWidth(w)

			#chapter_area = QTextDocument()
			#chapter_area.setDefaultFont(option.font)
			#chapter_area.setHtml("""
			#<font color="black">{}</font>
			#""".format("chapter"))
			#chapter_area.setTextWidth(w)
			def center_img(width):
				new_x = x
				if width < w:
					diff = w - width
					offset = diff//2
					new_x += offset
				return new_x

			def img_too_big(start_x):
				txt_layout = misc.text_layout("Image is too big!", w, self.title_font, self.title_font_m)

				clipping = QRectF(x, y+h//4, w, app_constants.GRIDBOX_LBL_H - 10)
				txt_layout.draw(painter, QPointF(x, y+h//4),
					  clip=clipping)

			# if we can't find a cached image
			pix_cache = QPixmapCache.find(self.key(gallery.profile))
			if isinstance(pix_cache, QPixmap):
				self.image = pix_cache
				img_x = center_img(self.image.width())
				if self.image.width() > w or self.image.height() > h:
					img_too_big(img_x)
				else:
					if self.image.height() < self.image.width(): #to keep aspect ratio
						painter.drawPixmap(QPoint(img_x,y),
								self.image)
					else:
						painter.drawPixmap(QPoint(img_x,y),
								self.image)
			else:
				self.image = QPixmap(gallery.profile)
				img_x = center_img(self.image.width())
				QPixmapCache.insert(self.key(gallery.profile), self.image)
				if self.image.width() > w or self.image.height() > h:
					img_too_big(img_x)
				else:
					if self.image.height() < self.image.width(): #to keep aspect ratio
						painter.drawPixmap(QPoint(img_x,y),
								self.image)
					else:
						painter.drawPixmap(QPoint(img_x,y),
								self.image)

			# draw ribbon type
			painter.save()
			painter.setPen(Qt.NoPen)
			if app_constants.DISPLAY_GALLERY_RIBBON:
				type_ribbon_w = type_ribbon_l = w*0.11
				rib_top_1 = QPointF(x+w-type_ribbon_l-type_ribbon_w, y)
				rib_top_2 = QPointF(x+w-type_ribbon_l, y)
				rib_side_1 = QPointF(x+w, y+type_ribbon_l)
				rib_side_2 = QPointF(x+w, y+type_ribbon_l+type_ribbon_w)
				ribbon_polygon = QPolygonF([rib_top_1, rib_top_2, rib_side_1, rib_side_2])
				ribbon_path = QPainterPath()
				ribbon_path.setFillRule(Qt.WindingFill)
				ribbon_path.addPolygon(ribbon_polygon)
				ribbon_path.closeSubpath()
				painter.setBrush(QBrush(QColor(self._ribbon_color(gallery.type))))
				painter.drawPath(ribbon_path)

			# draw if favourited
			if gallery.fav == 1:
				star_ribbon_w = star_ribbon_l = w*0.08
				rib_top_1 = QPointF(x+star_ribbon_l, y)
				rib_side_1 = QPointF(x, y+star_ribbon_l)
				rib_top_2 = QPointF(x+star_ribbon_l+star_ribbon_w, y)
				rib_side_2 = QPointF(x, y+star_ribbon_l+star_ribbon_w)
				rib_star_mid_1 = QPointF((rib_top_1.x()+rib_side_1.x())/2, (rib_top_1.y()+rib_side_1.y())/2)
				rib_star_factor = star_ribbon_l/4
				rib_star_p1_1 = rib_star_mid_1 + QPointF(rib_star_factor, -rib_star_factor)
				rib_star_p1_2 = rib_star_p1_1 + QPointF(-rib_star_factor, -rib_star_factor)
				rib_star_p1_3 = rib_star_mid_1 + QPointF(-rib_star_factor, rib_star_factor)
				rib_star_p1_4 = rib_star_p1_3 + QPointF(-rib_star_factor, -rib_star_factor)

				crown_1 = QPolygonF([rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3])
				painter.setBrush(QBrush(QColor("yellow")))
				painter.drawPolygon(crown_1)

				ribbon_polygon = QPolygonF([rib_top_1, rib_side_1, rib_side_2, rib_top_2])
				ribbon_path = QPainterPath()
				ribbon_path.setFillRule(Qt.WindingFill)
				ribbon_path.addPolygon(ribbon_polygon)
				ribbon_path.closeSubpath()
				painter.drawPath(ribbon_path)
				#painter.setPen(QColor("#d35400"))
				#painter.drawPolyline(rib_top_1, rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3, rib_side_1)
				#painter.drawLine(rib_top_1, rib_top_2)
				#painter.drawLine(rib_top_2, rib_side_2)
				#painter.drawLine(rib_side_1, rib_side_2)
			painter.restore()
			
			if app_constants._REFRESH_EXTERNAL_VIEWER:
				if app_constants.USE_EXTERNAL_VIEWER:
					self.external_icon = self.file_icons.get_external_file_icon()
				else:
					self.external_icon = self.file_icons.get_default_file_icon()
			
			if gallery.state == self.G_DOWNLOAD:
				painter.save()
				dl_box = QRect(x, y, w, 20)
				painter.setBrush(QBrush(QColor(0,0,0,123)))
				painter.setPen(QColor('white'))
				painter.drawRect(dl_box)
				painter.drawText(dl_box, Qt.AlignCenter, 'Downloading...')
				painter.restore()
			else:
				if app_constants.DISPLAY_GALLERY_TYPE:
					self.type_icon = self.file_icons.get_file_icon(gallery.path)
					if self.type_icon and not self.type_icon.isNull():
						self.type_icon.paint(painter, QRect(x+2, y+app_constants.THUMB_H_SIZE-16, 16, 16))

				if app_constants.USE_EXTERNAL_PROG_ICO:
					if self.external_icon and not self.external_icon.isNull():
						self.external_icon.paint(painter, QRect(x+w-30, y+app_constants.THUMB_H_SIZE-28, 28, 28))

			def draw_text_label(lbl_h):
				#draw the label for text
				painter.save()
				painter.translate(x, y+app_constants.THUMB_H_SIZE)
				box_color = QBrush(QColor(label_color))#QColor(0,0,0,123))
				painter.setBrush(box_color)
				rect = QRect(0, 0, w, lbl_h) #x, y, width, height
				painter.fillRect(rect, box_color)
				painter.restore()
				return rect

			if option.state & QStyle.State_MouseOver or\
			    option.state & QStyle.State_Selected:
				title_layout = misc.text_layout(title, w, self.title_font, self.title_font_m)
				artist_layout = misc.text_layout(artist, w, self.artist_font, self.artist_font_m)
				t_h = title_layout.boundingRect().height()
				a_h = artist_layout.boundingRect().height()

				if app_constants.GALLERY_FONT_ELIDE:
					lbl_rect = draw_text_label(min(t_h+a_h+3, app_constants.GRIDBOX_LBL_H))
				else:
					lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H)

				clipping = QRectF(x, y+app_constants.THUMB_H_SIZE, w, app_constants.GRIDBOX_LBL_H - 10)
				painter.setPen(QColor(title_color))
				title_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE),
					  clip=clipping)
				painter.setPen(QColor(artist_color))
				artist_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE+t_h),
					   clip=clipping)
				#painter.fillRect(option.rect, QColor)
			else:
				if app_constants.GALLERY_FONT_ELIDE:
					lbl_rect = draw_text_label(self.text_label_h)
				else:
					lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H)
				# draw text
				painter.save()
				alignment = QTextOption(Qt.AlignCenter)
				alignment.setUseDesignMetrics(True)
				title_rect = QRectF(0,0,w, self.title_font_m.height())
				artist_rect = QRectF(0,self.artist_font_m.height(),w,
						 self.artist_font_m.height())
				painter.translate(x, y+app_constants.THUMB_H_SIZE)
				if app_constants.GALLERY_FONT_ELIDE:
					painter.setFont(self.title_font)
					painter.setPen(QColor(title_color))
					painter.drawText(title_rect,
							 self.title_font_m.elidedText(title, Qt.ElideRight, w-10),
							 alignment)
				
					painter.setPen(QColor(artist_color))
					painter.setFont(self.artist_font)
					alignment.setWrapMode(QTextOption.NoWrap)
					painter.drawText(artist_rect,
								self.title_font_m.elidedText(artist, Qt.ElideRight, w-10),
								alignment)
				else:
					text_area.setDefaultFont(QFont(self.font_name))
					text_area.drawContents(painter)
				##painter.resetTransform()
				painter.restore()

			if option.state & QStyle.State_Selected:
				painter.save()
				selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE)
				painter.setPen(Qt.NoPen)
				painter.setBrush(QBrush(QColor(164,164,164,120)))
				painter.drawRoundedRect(selected_rect, 5, 5)
				#painter.fillRect(selected_rect, QColor(164,164,164,120))
				painter.restore()

			if gallery.dead_link:
				painter.save()
				selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE)
				painter.setPen(Qt.NoPen)
				painter.setBrush(QBrush(QColor(255,0,0,120)))
				p_path = QPainterPath()
				p_path.setFillRule(Qt.WindingFill)
				p_path.addRoundedRect(selected_rect, 5,5)
				p_path.addRect(x,y, 20, 20)
				p_path.addRect(x+w-20,y, 20, 20)
				painter.drawPath(p_path.simplified())
				painter.setPen(QColor("white"))
				txt_layout = misc.text_layout("Cannot find gallery source!", w, self.title_font, self.title_font_m)
				txt_layout.draw(painter, QPointF(x, y+h*0.3))
				painter.restore()

			if app_constants.DEBUG:
				painter.save()
				painter.setBrush(QBrush(QColor("red")))
				painter.setPen(QColor("white"))
				txt_l = self.title_font_m.width(str(gallery.id))
				painter.drawRect(x, y+40, txt_l*2, self.title_font_m.height())
				painter.drawText(x+1, y+51, str(gallery.id))
				painter.restore()
			if option.state & QStyle.State_Selected:
				painter.setPen(QPen(option.palette.highlightedText().color()))
		else:
			super().paint(painter, option, index)