コード例 #1
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))
コード例 #2
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()
コード例 #3
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)
コード例 #4
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)
コード例 #5
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
コード例 #6
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()
コード例 #7
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
コード例 #8
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
コード例 #9
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)
コード例 #10
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)
コード例 #11
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
コード例 #12
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))
コード例 #13
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()
コード例 #14
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()
コード例 #15
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()
コード例 #16
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)))
コード例 #17
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)
コード例 #18
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)
コード例 #19
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()
コード例 #20
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
コード例 #21
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')
コード例 #22
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)))
コード例 #23
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)))
コード例 #24
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())
コード例 #25
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
コード例 #26
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()
コード例 #27
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")
コード例 #28
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
コード例 #29
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
コード例 #30
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()