Esempio n. 1
0
class SwitcherSeparatorItem(SwitcherBaseItem):
    """
    Separator Item represented as <hr>.

    Based on HTML delegate.

    See: https://doc.qt.io/qt-5/richtext-html-subset.html
    """

    _SEPARATOR = '_'
    _HEIGHT = 15
    _STYLE_ATTRIBUTES = ['color', 'font_size']
    _STYLES = {
        'color': QApplication.palette().text().color().name(),
        'font_size': 10,
    }
    _TEMPLATE = \
        '''<table cellpadding="{padding}" cellspacing="0" width="{width}"
                  height="{height}" border="0">
  <tr><td valign="top" align="center"><hr></td></tr>
</table>'''

    def __init__(self, parent=None, styles=_STYLES):
        """Separator Item represented as <hr>."""
        super(SwitcherSeparatorItem, self).__init__(parent=parent,
                                                    styles=styles)
        self.setFlags(Qt.NoItemFlags)
        self._set_rendered_text()

    # --- Helpers
    def _set_styles(self):
        """Set the styles for this item."""
        for attr in self._STYLE_ATTRIBUTES:
            if attr not in self._styles:
                self._styles[attr] = self._STYLES[attr]

        rich_font = self._styles['font_size']

        if sys.platform == 'darwin':
            font_size = rich_font
        elif os.name == 'nt':
            font_size = rich_font
        elif is_ubuntu():
            font_size = rich_font - 2
        else:
            font_size = rich_font - 2

        self._styles['font_size'] = font_size

    def _render_text(self):
        """Render the html template for this item."""
        padding = self._padding
        width = self._width
        height = self._HEIGHT
        text = self._TEMPLATE.format(width=width,
                                     height=height,
                                     padding=padding,
                                     **self._styles)
        return text
Esempio n. 2
0
    def __init__(self, parent=None):
        super(WidgetGallery, self).__init__(parent)

        self.originalPalette = QApplication.palette()

        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())

        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)

        self.useStylePaletteCheckBox = QCheckBox(
            "&Use style's standard palette")
        self.useStylePaletteCheckBox.setChecked(True)

        disableWidgetsCheckBox = QCheckBox("&Disable widgets")

        self.createTopLeftGroupBox()
        self.createTopRightGroupBox()
        self.createBottomLeftTabWidget()
        self.createBottomRightGroupBox()
        self.createProgressBar()

        styleComboBox.activated[str].connect(self.changeStyle)
        self.useStylePaletteCheckBox.toggled.connect(self.changePalette)
        disableWidgetsCheckBox.toggled.connect(
            self.topLeftGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(
            self.topRightGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(
            self.bottomLeftTabWidget.setDisabled)
        disableWidgetsCheckBox.toggled.connect(
            self.bottomRightGroupBox.setDisabled)

        topLayout = QHBoxLayout()
        topLayout.addWidget(styleLabel)
        topLayout.addWidget(styleComboBox)
        topLayout.addStretch(1)
        topLayout.addWidget(self.useStylePaletteCheckBox)
        topLayout.addWidget(disableWidgetsCheckBox)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.topLeftGroupBox, 1, 0)
        mainLayout.addWidget(self.topRightGroupBox, 1, 1)
        mainLayout.addWidget(self.bottomLeftTabWidget, 2, 0)
        mainLayout.addWidget(self.bottomRightGroupBox, 2, 1)
        mainLayout.addWidget(self.progressBar, 3, 0, 1, 2)
        mainLayout.setRowStretch(1, 1)
        mainLayout.setRowStretch(2, 1)
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(1, 1)
        self.setLayout(mainLayout)

        self.changeStyle('Windows')

        self.val = 0
Esempio n. 3
0
    def paint(self, painter, option, index):
        data = self.model.data(index)

        style = QApplication.style()
        palette = QApplication.palette()

        # Draw the selection background
        if option.state & QStyle.State_Selected:
            painter.save()
            painter.setPen(Qt.NoPen)  # Removes border on the top and left
            painter.setBrush(palette.highlight())
            painter.drawRect(option.rect)
            painter.restore()

        # Draw the focus rectangle, there doesn't seem to be a simple way to do this.
        if option.state & QStyle.State_HasFocus:
            focus_style = QStyleOptionFocusRect()

            focus_style.state = option.state | QStyle.State_KeyboardFocusChange | QStyle.State_Item
            focus_style.direction = option.direction
            focus_style.fontMetrics = option.fontMetrics
            focus_style.styleObject = option.styleObject

            if style.objectName() == "windowsvista":
                # The Windows style for Qt seems to remove 1px from each side of the rect.
                # I'm sure that there is a way to do this without hard-coding, but I can't find it.
                focus_style.rect = QRect(option.rect.x() + 1, option.rect.y(),
                                         option.rect.width() - 2,
                                         option.rect.height())
            else:
                # If the theme is anything else, the normal rectangle of style option should suffice.
                focus_style.rect = option.rect

            focus_style.backgroundColor = option.palette.color(
                palette.Normal if option.state
                & QStyle.State_Enabled else palette.Disabled,
                palette.Highlight if option.state
                & QStyle.State_Selected else palette.Window)

            painter.save()
            style.drawPrimitive(QStyle.PE_FrameFocusRect, focus_style, painter)
            painter.restore()

        checkbox_style = QStyleOptionButton()
        checkbox_style.state |= QStyle.State_Enabled if option.state & QStyle.State_Enabled else QStyle.State_NoChange
        checkbox_style.state |= QStyle.State_On if data else QStyle.State_Off
        checkbox_style.rect = self.__get_checkbox_rect(option)

        painter.save()
        style.drawControl(QStyle.CE_CheckBox, checkbox_style, painter)
        painter.restore()
Esempio n. 4
0
    def paint(self, painter, option: QStyleOptionViewItem,
              index: QModelIndex) -> None:
        data = index.data(ProgressRole)
        nr_reals = 0
        status = {}
        if data:
            nr_reals = data["nr_reals"]
            status = data["status"]

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

        background_color = QApplication.palette().color(QPalette.Window)
        painter.fillRect(option.rect.x(), option.rect.y(), option.rect.width(),
                         30, background_color)

        total_states = len(REAL_STATE_TO_COLOR.items())
        d = math.ceil(option.rect.width() / total_states)
        x_pos = 0
        for state, color_ref in REAL_STATE_TO_COLOR.items():

            state_progress = 0
            if state in status:
                state_progress = status[state]

            x = x_pos
            y = option.rect.y()
            w = d
            h = option.rect.height()
            margin = 5

            painter.setBrush(QColor(*color_ref))
            painter.drawRect(x, y + margin, 20, 20)
            painter.drawText(
                x + 25,
                y + margin,
                w - 25,
                h,
                Qt.AlignLeft,
                f"{state} ({state_progress}/{nr_reals})",
            )
            x_pos += d

        painter.restore()
Esempio n. 5
0
 def _set_active_data(self, index, is_active):
     font = self.data(index, Qt.FontRole) or QFont()
     if is_active is True:
         if self.active_ensemble is not None:
             # self.active_ensemble.setData(False, self.active_role)
             active_index = self.index(self.active_ensemble.row(), 0)
             self.setData(active_index, False, self.active_role)
         self.active_ensemble = self.getItem(index)
         self._update_title(self.active_ensemble_name)
         palette = QApplication.palette()
         brush = palette.color(QPalette.Normal, QPalette.Highlight)
         text_brush = palette.color(QPalette.Normal, QPalette.BrightText)
         font.setBold(True)
     else:
         self.active_ensemble = None
         self._update_title(self.active_ensemble_name)
         brush = QBrush()
         text_brush = QBrush()
         font.setBold(False)
     self.setData(index, brush, Qt.BackgroundRole)
     self.setData(index, text_brush, Qt.ForegroundRole)
     self.setData(index, font, Qt.FontRole)
Esempio n. 6
0
class SwitcherItem(SwitcherBaseItem):
    """
    Switcher item with title, description, shortcut and section.

    SwitcherItem: [title description    <shortcut> section]

    Based on HTML delegate.
    See: https://doc.qt.io/qt-5/richtext-html-subset.html
    """

    _FONT_SIZE = 10
    _STYLE_ATTRIBUTES = ['title_color', 'description_color', 'section_color',
                         'shortcut_color', 'title_font_size',
                         'description_font_size', 'section_font_size',
                         'shortcut_font_size']
    _STYLES = {
        'title_color': QApplication.palette().text().color().name(),
        'description_color': 'rgb(153, 153, 153)',
        'section_color': 'rgb(70, 179, 239)',
        'shortcut_color': 'rgb(153, 153, 153)',
        'title_font_size': _FONT_SIZE,
        'description_font_size': _FONT_SIZE,
        'section_font_size': _FONT_SIZE,
        'shortcut_font_size': _FONT_SIZE,
    }
    _TEMPLATE = u'''
<table width="{width}" max_width="{width}" height="{height}"
                          cellpadding="{padding}">
  <tr>
    <td valign="middle">
      <span style="color:{title_color};font-size:{title_font_size}pt">
        {title}
      </span>&nbsp;
      <small
       style="color:{description_color};font-size:{description_font_size}pt">
        <span>{description}</span>
      </small>
    </td>
    <td valign="middle" align="right" float="right">
      <span style="color:{shortcut_color};font-size:{shortcut_font_size}pt">
         <small><code><i>{shortcut}</i></code></small>
      </span>&nbsp;
      <span style="color:{section_color};font-size:{section_font_size}pt">
         <small>{section}</small>
      </span>
    </td>
  </tr>
</table>'''

    def __init__(self, parent=None, icon=None, title=None, description=None,
                 shortcut=None, section=None, data=None, tool_tip=None,
                 action_item=False, styles=_STYLES):
        """Switcher item with title, description, shortcut and section."""
        super(SwitcherItem, self).__init__(parent=parent, styles=styles)

        self._title = title if title else ''
        self._rich_title = ''
        self._shortcut = shortcut if shortcut else ''
        self._description = description if description else ''
        self._section = section if section else ''
        self._icon = icon
        self._data = data
        self._score = -1
        self._action_item = action_item

        self._section_visible = True

        # Setup
        self.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        if icon:
            self.setIcon(icon)
            # TODO: Change fixed icon size value
            self._icon_width = 20
        else:
            self._icon_width = 0

        self._set_styles()
        self._set_rendered_text()

    # --- Helpers
    def _render_text(self, title=None, description=None, section=None):
        """Render the html template for this item."""
        if self._rich_title:
            title = self._rich_title
        else:
            title = title if title else self._title

        # TODO: Based on width this should elide/shorten
        description = description if description else self._description

        if self._section_visible:
            section = section if section else self._section
        else:
            section = ''

        padding = self._PADDING
        width = int(self._width - self._icon_width)
        height = int(self.get_height())
        self.setSizeHint(QSize(width, height))

        shortcut = '&lt;' + self._shortcut + '&gt;' if self._shortcut else ''

        title = to_text_string(title, encoding='utf-8')
        section = to_text_string(section, encoding='utf-8')
        description = to_text_string(description, encoding='utf-8')
        shortcut = to_text_string(shortcut, encoding='utf-8')

        text = self._TEMPLATE.format(width=width, height=height, title=title,
                                     section=section, description=description,
                                     padding=padding, shortcut=shortcut,
                                     **self._styles)
        return text

    def _set_styles(self):
        """Set the styles for this item."""
        for attr in self._STYLE_ATTRIBUTES:
            if attr not in self._styles:
                self._styles[attr] = self._STYLES[attr]

        rich_font = self._styles['title_font_size']

        if sys.platform == 'darwin':
            title_font_size = rich_font
            description_font_size = title_font_size + 2
        elif os.name == 'nt':
            title_font_size = rich_font
            description_font_size = title_font_size + 1
        elif is_ubuntu():
            title_font_size = rich_font - 2
            description_font_size = title_font_size + 1
        else:
            title_font_size = rich_font - 2
            description_font_size = title_font_size + 1

        self._styles['description_font_size'] = description_font_size
        self._styles['section_font_size'] = description_font_size

    def _get_height(self):
        """
        Return the expected height of this item's text, including
        the text margins.
        """
        doc = QTextDocument()
        try:
            doc.setHtml('<span style="font-size:{}pt">Title</span>'
                        .format(self._styles['title_font_size']))
        except KeyError:
            doc.setHtml('<span>Title</span>')
        doc.setDocumentMargin(self._PADDING)
        return doc.size().height()

    # --- API
    def set_icon(self, icon):
        """Set the QIcon for the list item."""
        self._icon = icon
        self.setIcon(icon)

    def get_icon(self):
        """Return the QIcon for the list item."""
        return self._icon

    def set_title(self, value):
        """Set the main text (title) of the item."""
        self._title = value
        self._set_rendered_text()

    def get_title(self):
        """Return the the main text (title) of the item."""
        return self._title

    def set_rich_title(self, value):
        """Set the rich title version (filter highlight) of the item."""
        self._rich_title = value
        self._set_rendered_text()

    def get_rich_title(self):
        """Return the rich title version (filter highlight) of the item."""
        return self._rich_title

    def set_description(self, value):
        """Set the item description text."""
        self._description = value
        self._set_rendered_text()

    def get_description(self):
        """Return the item description text."""
        return self._description

    def set_shortcut(self, value):
        """Set the shortcut for the item action."""
        self._shortcut = value
        self._set_rendered_text()

    def get_shortcut(self, value):
        """Return the shortcut for the item action."""
        return self._shortcut

    def set_tooltip(self, value):
        """Set the tooltip text for the item."""
        super(SwitcherItem, self).setTooltip(value)

    def set_data(self, value):
        """Set the additional data associated to the item."""
        self._data = value

    def get_data(self):
        """Return the additional data associated to the item."""
        return self._data

    def set_section(self, value):
        """Set the item section name."""
        self._section = value
        self._set_rendered_text()

    def get_section(self):
        """Return the item section name."""
        return self._section

    def set_section_visible(self, value):
        """Set visibility of the item section."""
        self._section_visible = value
        self._set_rendered_text()

    def set_action_item(self, value):
        """Enable/disable the action type for the item."""
        self._action_item = value
        self._set_rendered_text()