Ejemplo n.º 1
0
 def __elide(self):
     fm = QFontMetrics(self.__name_item.font())
     text = fm.elidedText(self.__name, Qt.ElideRight, self.__max_len)
     self.__name_item.setText(text)
     if self.__value is not None:
         fm = QFontMetrics(self.__value_item.font())
         text = fm.elidedText(self.__value, Qt.ElideRight, self.__max_len)
         self.__value_item.setText(text)
Ejemplo n.º 2
0
    def paintEvent(self, event):
        painter = QPainter(self)

        metrics = QFontMetrics(self.font())
        elided = metrics.elidedText(self.text(), Qt.ElideRight, self.width())

        painter.drawText(self.rect(), self.alignment(), elided)
Ejemplo n.º 3
0
    def __textLayout(self):
        fm = QFontMetrics(self.font())
        text = six.text_type(self.defaultAction().text())
        words = deque(text.split())

        lines = []
        curr_line = ""
        curr_line_word_count = 0

        option = QStyleOptionToolButton()
        option.initFrom(self)

        margin = self.style().pixelMetric(QStyle.PM_ButtonMargin, option, self)
        width = self.width() - 2 * margin

        while words:
            w = words.popleft()

            if curr_line_word_count:
                line_extended = " ".join([curr_line, w])
            else:
                line_extended = w

            line_w = fm.boundingRect(line_extended).width()

            if line_w >= width:
                if curr_line_word_count == 0 or len(lines) == 1:
                    # A single word that is too long must be elided.
                    # Also if the text overflows 2 lines
                    # Warning: hardcoded max lines
                    curr_line = fm.elidedText(line_extended, Qt.ElideRight,
                                              width)
                    curr_line = six.text_type(curr_line)
                else:
                    # Put the word back
                    words.appendleft(w)

                lines.append(curr_line)
                curr_line = ""
                curr_line_word_count = 0
                if len(lines) == 2:
                    break
            else:
                curr_line = line_extended
                curr_line_word_count += 1

        if curr_line:
            lines.append(curr_line)

        text = "\n".join(lines)
        text = text.replace('&', '&&')  # Need escaped ampersand to show

        self.__text = text
Ejemplo n.º 4
0
    def __textLayout(self):
        fm = QFontMetrics(self.font())
        text = self.defaultAction().text()
        words = deque(text.split())

        lines = []
        curr_line = ""
        curr_line_word_count = 0

        option = QStyleOptionToolButton()
        option.initFrom(self)

        margin = self.style().pixelMetric(QStyle.PM_ButtonMargin, option, self)
        width = self.width() - 2 * margin

        while words:
            w = words.popleft()

            if curr_line_word_count:
                line_extended = " ".join([curr_line, w])
            else:
                line_extended = w

            line_w = fm.boundingRect(line_extended).width()

            if line_w >= width:
                if curr_line_word_count == 0 or len(lines) == 1:
                    # A single word that is too long must be elided.
                    # Also if the text overflows 2 lines
                    # Warning: hardcoded max lines
                    curr_line = fm.elidedText(line_extended, Qt.ElideRight,
                                              width)
                    curr_line = curr_line
                else:
                    # Put the word back
                    words.appendleft(w)

                lines.append(curr_line)
                curr_line = ""
                curr_line_word_count = 0
                if len(lines) == 2:
                    break
            else:
                curr_line = line_extended
                curr_line_word_count += 1

        if curr_line:
            lines.append(curr_line)

        text = "\n".join(lines)
        text = text.replace('&', '&&')  # Need escaped ampersand to show

        self.__text = text
Ejemplo n.º 5
0
def show_tool_tip(pos: QPoint, text: str, widget: Optional[QWidget] = None,
                  rect=QRect(), elide=Qt.ElideRight):
    """
    Show a plain text tool tip with limited length, eliding if necessary.
    """
    if widget is not None:
        screen = widget.screen()
    else:
        screen = QApplication.screenAt(pos)
    font = QApplication.font("QTipLabel")
    fm = QFontMetrics(font)
    geom = screen.availableSize()
    etext = fm.elidedText(text, elide, geom.width())
    if etext != text:
        text = f"<span>{etext}</span>"
    QToolTip.showText(pos, text, widget, rect)
Ejemplo n.º 6
0
 def paintEvent(self, event):
     QLineEdit.paintEvent(self, event)
     if not self.text() and self.placeholderText(
     ) and not self.hasFocus():
         p = QStylePainter(self)
         font = self.font()
         metrics = QFontMetrics(font)
         p.setFont(font)
         color = self.palette().color(QPalette.Mid)
         p.setPen(color)
         left, top, right, bottom = self.getTextMargins()
         contents = self.contentsRect()
         contents = contents.adjusted(left, top, -right, -bottom)
         text = metrics.elidedText(self.placeholderText(),
                                   Qt.ElideMiddle, contents.width())
         p.drawText(contents, Qt.AlignLeft | Qt.AlignVCenter, text)
Ejemplo n.º 7
0
def set_widget_value(widget, value):
    if isinstance(widget, QLineEdit):
        widget.setText(value)
    elif isinstance(widget, QPlainTextEdit):
        return widget.setPlainText(value)
    elif isinstance(widget, QLabel):
        if widget.openExternalLinks():
            widget.setToolTip(value)
            metrics = QFontMetrics(widget.font())
            display = metrics.elidedText(value, Qt.ElideRight, widget.width())
            value = urllib.parse.unquote(value)     # Because setText() escapes percent-encoded values and corrupts them
            value = '<a href="{value}">{display}</a>'.format(**locals())
        widget.setText(value)
    elif isinstance(widget, QCheckBox):
        return widget.setChecked(value not in (False, '0', '', 'False'))
    else:
        raise RuntimeError()
Ejemplo n.º 8
0
 def __static_text_elided_cache(
         self, text: str, font: QFont, fontMetrics: QFontMetrics,
         elideMode: Qt.TextElideMode, width: int
 ) -> QStaticText:
     """
     Return a `QStaticText` instance for depicting the text with the `font`
     """
     try:
         return self.__static_text_lru_cache[text, font, elideMode, width]
     except KeyError:
         text = fontMetrics.elidedText(text, elideMode, width)
         st = QStaticText(text)
         st.prepare(QTransform(), font)
         # take a copy of the font for cache key
         key = text, QFont(font), elideMode, width
         self.__static_text_lru_cache[key] = st
         return st
Ejemplo n.º 9
0
 def paintEvent(self, event):
     QLineEdit.paintEvent(self, event)
     if not self.text() and self.placeholderText() and \
             not self.hasFocus():
         p = QStylePainter(self)
         font = self.font()
         metrics = QFontMetrics(font)
         p.setFont(font)
         color = self.palette().color(QPalette.Mid)
         p.setPen(color)
         left, top, right, bottom = self.getTextMargins()
         contents = self.contentsRect()
         contents = contents.adjusted(left, top, -right, -bottom)
         text = metrics.elidedText(self.placeholderText(),
                                   Qt.ElideMiddle,
                                   contents.width())
         p.drawText(contents, Qt.AlignLeft | Qt.AlignVCenter, text)
Ejemplo n.º 10
0
    def __paintEventNoStyle(self):
        p = QPainter(self)
        opt = QStyleOptionToolButton()
        self.initStyleOption(opt)

        fm = QFontMetrics(opt.font)
        palette = opt.palette

        # highlight brush is used as the background for the icon and background
        # when the tab is expanded and as mouse hover color (lighter).
        brush_highlight = palette.highlight()
        if opt.state & QStyle.State_Sunken:
            # State 'down' pressed during a mouse press (slightly darker).
            background_brush = brush_darker(brush_highlight, 110)
        elif opt.state & QStyle.State_MouseOver:
            background_brush = brush_darker(brush_highlight, 95)
        elif opt.state & QStyle.State_On:
            background_brush = brush_highlight
        else:
            # The default button brush.
            background_brush = palette.button()

        rect = opt.rect

        icon_area_rect = QRect(rect)
        icon_area_rect.setRight(int(icon_area_rect.height() * 1.26))

        text_rect = QRect(rect)
        text_rect.setLeft(icon_area_rect.right() + 10)

        # Background  (TODO: Should the tab button have native
        # toolbutton shape, drawn using PE_PanelButtonTool or even
        # QToolBox tab shape)

        # Default outline pen
        pen = QPen(palette.color(QPalette.Mid))

        p.save()
        p.setPen(Qt.NoPen)
        p.setBrush(QBrush(background_brush))
        p.drawRect(rect)

        # Draw the background behind the icon if the background_brush
        # is different.
        if not opt.state & QStyle.State_On:
            p.setBrush(brush_highlight)
            p.drawRect(icon_area_rect)
            # Line between the icon and text
            p.setPen(pen)
            p.drawLine(icon_area_rect.topRight(),
                       icon_area_rect.bottomRight())

        if opt.state & QStyle.State_HasFocus:
            # Set the focus frame pen and draw the border
            pen = QPen(QColor(FOCUS_OUTLINE_COLOR))
            p.setPen(pen)
            p.setBrush(Qt.NoBrush)
            # Adjust for pen
            rect = rect.adjusted(0, 0, -1, -1)
            p.drawRect(rect)

        else:
            p.setPen(pen)
            # Draw the top/bottom border
            if self.position == QStyleOptionToolBox.OnlyOneTab or \
                    self.position == QStyleOptionToolBox.Beginning or \
                    self.selected & \
                        QStyleOptionToolBox.PreviousIsSelected:

                p.drawLine(rect.topLeft(), rect.topRight())

            p.drawLine(rect.bottomLeft(), rect.bottomRight())

        p.restore()

        p.save()
        text = fm.elidedText(opt.text, Qt.ElideRight, text_rect.width())
        p.setPen(QPen(palette.color(QPalette.ButtonText)))
        p.setFont(opt.font)

        p.drawText(text_rect,
                   int(Qt.AlignVCenter | Qt.AlignLeft) | \
                   int(Qt.TextSingleLine),
                   text)

        if not opt.icon.isNull():
            if opt.state & QStyle.State_Enabled:
                mode = QIcon.Normal
            else:
                mode = QIcon.Disabled
            if opt.state & QStyle.State_On:
                state = QIcon.On
            else:
                state = QIcon.Off
            icon_area_rect = icon_area_rect
            icon_rect = QRect(QPoint(0, 0), opt.iconSize)
            icon_rect.moveCenter(icon_area_rect.center())
            opt.icon.paint(p, icon_rect, Qt.AlignCenter, mode, state)
        p.restore()
Ejemplo n.º 11
0
 def set_text(self):
     metrics = QFontMetrics(self.font())
     self.setText(
         metrics.elidedText(self.desc_text, Qt.ElideRight,
                            self.width() - 15))
Ejemplo n.º 12
0
    def __layout(self) -> None:
        margins = QMarginsF(*self.getContentsMargins())
        if self.__orientation == Qt.Horizontal:
            # transposed margins
            margins = QMarginsF(
                margins.bottom(), margins.left(), margins.top(), margins.right()
            )
            crect = self.rect().transposed().marginsRemoved(margins)
        else:
            crect = self.rect().marginsRemoved(margins)

        spacing = self.__spacing

        align_horizontal = self.__alignment & Qt.AlignHorizontal_Mask
        align_vertical = self.__alignment & Qt.AlignVertical_Mask
        if align_vertical == 0:
            align_vertical = Qt.AlignTop
        if align_horizontal == 0:
            align_horizontal = Qt.AlignLeft

        N = len(self.__items)

        if not N:
            return

        assert self.__group is not None
        font = self.font()
        fm = QFontMetrics(font)

        fontheight = fm.height()
        # the available vertical space
        vspace = crect.height() - (N - 1) * spacing
        cell_height = vspace / N

        if cell_height > fontheight:
            # use font height, adjust (widen) spacing.
            cell_height = fontheight
            spacing = (crect.height() - N * cell_height) / N
        elif self.__autoScale:
            # find a smaller font size to fit the height
            psize = effective_point_size_for_height(font, cell_height)
            font.setPointSizeF(psize)
            fm = QFontMetrics(font)
            fontheight = fm.height()

        if self.__autoScale and self.__effectiveFont != font:
            self.__effectiveFont = font
            apply_all(self.__textitems, lambda it: it.setFont(font))

        if self.__elideMode != Qt.ElideNone:
            if self.__orientation == Qt.Vertical:
                textwidth = math.ceil(crect.width())
            else:
                textwidth = math.ceil(crect.height())
            for text, item in zip(self.__items, self.__textitems):
                textelide = fm.elidedText(
                    text, self.__elideMode, textwidth, Qt.TextSingleLine
                )
                item.setText(textelide)

        advance = cell_height + spacing
        if align_vertical == Qt.AlignTop:
            align_dy = 0.
        elif align_vertical == Qt.AlignVCenter:
            align_dy = advance / 2.0 - fontheight / 2.0
        else:
            align_dy = advance - fontheight

        if align_horizontal == Qt.AlignLeft:
            for i, item in enumerate(self.__textitems):
                item.setPos(crect.left(), crect.top() + i * advance + align_dy)
        elif align_horizontal == Qt.AlignHCenter:
            for i, item in enumerate(self.__textitems):
                item.setPos(
                    crect.center().x() - item.boundingRect().width() / 2,
                    crect.top() + i * advance + align_dy
                )
        else:
            for i, item in enumerate(self.__textitems):
                item.setPos(
                    crect.right() - item.boundingRect().width(),
                    crect.top() + i * advance + align_dy
                )

        if self.__orientation == Qt.Vertical:
            self.__group.setRotation(0)
            self.__group.setPos(0, 0)
        else:
            self.__group.setRotation(-90)
            self.__group.setPos(self.rect().bottomLeft())
Ejemplo n.º 13
0
 def set_text(self):
     metrics = QFontMetrics(self.font())
     self.setText(metrics.elidedText(self.desc_text, Qt.ElideRight,
                                     self.width() - 15))
Ejemplo n.º 14
0
    def __paintEventNoStyle(self):
        p = QPainter(self)
        opt = QStyleOptionToolButton()
        self.initStyleOption(opt)

        fm = QFontMetrics(opt.font)
        palette = opt.palette

        # highlight brush is used as the background for the icon and background
        # when the tab is expanded and as mouse hover color (lighter).
        brush_highlight = palette.highlight()
        foregroundrole = QPalette.ButtonText
        if opt.state & QStyle.State_Sunken:
            # State 'down' pressed during a mouse press (slightly darker).
            background_brush = brush_darker(brush_highlight, 110)
            foregroundrole = QPalette.HighlightedText
        elif opt.state & QStyle.State_MouseOver:
            background_brush = brush_darker(brush_highlight, 95)
            foregroundrole = QPalette.HighlightedText
        elif opt.state & QStyle.State_On:
            background_brush = brush_highlight
            foregroundrole = QPalette.HighlightedText
        else:
            # The default button brush.
            background_brush = palette.button()

        rect = opt.rect

        icon_area_rect = QRect(rect)
        icon_area_rect.setRight(int(icon_area_rect.height() * 1.26))

        text_rect = QRect(rect)
        text_rect.setLeft(icon_area_rect.right() + 10)

        # Background  (TODO: Should the tab button have native
        # toolbutton shape, drawn using PE_PanelButtonTool or even
        # QToolBox tab shape)

        # Default outline pen
        pen = QPen(palette.color(QPalette.Mid))

        p.save()
        p.setPen(Qt.NoPen)
        p.setBrush(QBrush(background_brush))
        p.drawRect(rect)

        # Draw the background behind the icon if the background_brush
        # is different.
        if not opt.state & QStyle.State_On:
            p.setBrush(brush_highlight)
            p.drawRect(icon_area_rect)
            # Line between the icon and text
            p.setPen(pen)
            p.drawLine(icon_area_rect.topRight(),
                       icon_area_rect.bottomRight())

        if opt.state & QStyle.State_HasFocus:
            # Set the focus frame pen and draw the border
            pen = QPen(QColor(FOCUS_OUTLINE_COLOR))
            p.setPen(pen)
            p.setBrush(Qt.NoBrush)
            # Adjust for pen
            rect = rect.adjusted(0, 0, -1, -1)
            p.drawRect(rect)

        else:
            p.setPen(pen)
            # Draw the top/bottom border
            if self.position == QStyleOptionToolBox.OnlyOneTab or \
                    self.position == QStyleOptionToolBox.Beginning or \
                    self.selected & \
                        QStyleOptionToolBox.PreviousIsSelected:

                p.drawLine(rect.topLeft(), rect.topRight())

            p.drawLine(rect.bottomLeft(), rect.bottomRight())

        p.restore()

        p.save()
        text = fm.elidedText(opt.text, Qt.ElideRight, text_rect.width())
        p.setPen(QPen(palette.color(foregroundrole)))
        p.setFont(opt.font)

        p.drawText(text_rect,
                   int(Qt.AlignVCenter | Qt.AlignLeft) | \
                   int(Qt.TextSingleLine),
                   text)

        if not opt.icon.isNull():
            if opt.state & QStyle.State_Enabled:
                mode = QIcon.Normal
            else:
                mode = QIcon.Disabled
            if opt.state & QStyle.State_On:
                state = QIcon.On
            else:
                state = QIcon.Off
            icon_area_rect = icon_area_rect
            icon_rect = QRect(QPoint(0, 0), opt.iconSize)
            icon_rect.moveCenter(icon_area_rect.center())
            opt.icon.paint(p, icon_rect, Qt.AlignCenter, mode, state)
        p.restore()