예제 #1
0
def shadowTemplatePixmap(color, length):
    """
    Returns 1 pixel wide, `length` pixels long linear-gradient.

    Args:
        color (QColor): shadow color
        length (int): length of cast shadow

    """
    key = "InnerShadowTemplate " + \
          color.name() + " " + \
          str(length)

    # get cached template
    shadowPixmap = QPixmapCache.find(key)
    if shadowPixmap:
        return shadowPixmap

    shadowPixmap = QPixmap(1, length)
    shadowPixmap.fill(Qt.transparent)

    grad = QLinearGradient(0, 0, 0, length)
    grad.setColorAt(0, color)
    grad.setColorAt(1, Qt.transparent)

    painter = QPainter()
    painter.begin(shadowPixmap)
    painter.fillRect(shadowPixmap.rect(), grad)
    painter.end()

    # cache template
    QPixmapCache.insert(key, shadowPixmap)

    return shadowPixmap
예제 #2
0
    def __updatePixmap(self):
        """
        Update the cached shadow pixmap.
        """
        rect_size = QSize(50, 50)
        left = top = right = bottom = self.radius_

        # Size of the pixmap.
        pixmap_size = QSize(rect_size.width() + left + right,
                            rect_size.height() + top + bottom)
        shadow_rect = QRect(QPoint(left, top), rect_size)
        pixmap = QPixmap(pixmap_size)
        pixmap.fill(QColor(0, 0, 0, 0))
        rect_fill_color = self.palette().color(QPalette.Window)

        pixmap = render_drop_shadow_frame(
            pixmap,
            QRectF(shadow_rect),
            shadow_color=self.color_,
            offset=QPointF(0, 0),
            radius=self.radius_,
            rect_fill_color=rect_fill_color,
        )

        self.__shadowPixmap = pixmap
        self.update()
예제 #3
0
    def pixmap(self, size, mode, state):
        # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap
        if not self.__generator.isValid():
            return QPixmap()

        dsize = self.__generator.defaultSize()  # type: QSize
        if not dsize.isNull():
            dsize.scale(size, Qt.KeepAspectRatio)
            size = dsize
        key = "{}.SVGIconEngine/{}/{}x{}".format(__name__, self.__cache_id,
                                                 size.width(), size.height())
        pm = QPixmapCache.find(key)
        if pm is None or pm.isNull():
            pm = QPixmap(size)
            pm.fill(Qt.transparent)
            painter = QPainter(pm)
            try:
                self.__generator.render(
                    painter, QRectF(0, 0, size.width(), size.height()))
            finally:
                painter.end()
            QPixmapCache.insert(key, pm)
        style = QApplication.style()
        if style is not None:
            opt = QStyleOption()
            opt.palette = QApplication.palette()
            pm = style.generatedIconPixmap(mode, pm, opt)
        return pm
예제 #4
0
def decorate_welcome_icon(icon, background_color):
    """Return a `QIcon` with a circle shaped background.
    """
    welcome_icon = QIcon()
    sizes = [32, 48, 64, 80, 128, 256]
    background_color = NAMED_COLORS.get(background_color, background_color)
    background_color = QColor(background_color)
    grad = radial_gradient(background_color)
    for size in sizes:
        icon_size = QSize(5 * size / 8, 5 * size / 8)
        icon_rect = QRect(QPoint(0, 0), icon_size)
        pixmap = QPixmap(size, size)
        pixmap.fill(Qt.transparent)
        p = QPainter(pixmap)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.setBrush(QBrush(grad))
        p.setPen(Qt.NoPen)
        ellipse_rect = QRect(0, 0, size, size)
        p.drawEllipse(ellipse_rect)
        icon_rect.moveCenter(ellipse_rect.center())
        icon.paint(p, icon_rect, Qt.AlignCenter, )
        p.end()

        welcome_icon.addPixmap(pixmap)

    return welcome_icon
    def test(self):
        img = QImage(100, 100, QImage.Format_ARGB32)
        img.fill(Qt.green)
        p = QPainter(img)
        pix = QPixmap(10, 10)
        pix.fill(Qt.red)
        frgmts = [
            QPainter.PixmapFragment.create(
                QPointF(25, 25),
                QRectF(0, 0, 10, 10),
                5., 5.,
            ),
            QPainter.PixmapFragment.create(
                QPointF(75, 75),
                QRectF(0, 0, 10, 10),
                5., 5.,
            )

        ]
        p.drawPixmapFragments(frgmts, pix)
        p.end()
        self.assertEqual(QColor(img.pixel(10, 10)), QColor(Qt.red))
        self.assertEqual(QColor(img.pixel(80, 80)),  QColor(Qt.red))
        self.assertEqual(QColor(img.pixel(90, 10)), QColor(Qt.green))
        self.assertEqual(QColor(img.pixel(10, 90)), QColor(Qt.green))
예제 #6
0
    def pixmap(self, size, mode, state):
        # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap
        if not self.__generator.isValid():
            return QPixmap()

        dsize = self.__generator.defaultSize()  # type: QSize
        if not dsize.isNull():
            dsize.scale(size, Qt.KeepAspectRatio)
            size = dsize
        key = "{}.SVGIconEngine/{}/{}x{}".format(
            __name__, self.__cache_id, size.width(), size.height()
        )
        pm = QPixmapCache.find(key)
        if pm is None or pm.isNull():
            pm = QPixmap(size)
            pm.fill(Qt.transparent)
            painter = QPainter(pm)
            try:
                self.__generator.render(
                    painter, QRectF(0, 0, size.width(), size.height()))
            finally:
                painter.end()
            QPixmapCache.insert(key, pm)
        style = QApplication.style()
        if style is not None:
            opt = QStyleOption()
            opt.palette = QApplication.palette()
            pm = style.generatedIconPixmap(mode, pm, opt)
        return pm
예제 #7
0
    def __updatePixmap(self):
        """
        Update the cached shadow pixmap.
        """
        rect_size = QSize(50, 50)
        left = top = right = bottom = self.radius_

        # Size of the pixmap.
        pixmap_size = QSize(rect_size.width() + left + right,
                            rect_size.height() + top + bottom)
        shadow_rect = QRect(QPoint(left, top), rect_size)
        pixmap = QPixmap(pixmap_size)
        pixmap.fill(QColor(0, 0, 0, 0))
        rect_fill_color = self.palette().color(QPalette.Window)

        pixmap = render_drop_shadow_frame(
                      pixmap,
                      QRectF(shadow_rect),
                      shadow_color=self.color_,
                      offset=QPointF(0, 0),
                      radius=self.radius_,
                      rect_fill_color=rect_fill_color
                      )

        self.__shadowPixmap = pixmap
        self.update()
예제 #8
0
    def __shadowPixmapForDpr(self, dpr=1.0):
        # type: (float) -> QPixmap
        """
        Return a shadow pixmap rendered in `dpr` device pixel ratio.
        """
        offset = self.offset()
        radius = self.radius()
        color = self.color()
        fill_color = self.palette().color(QPalette.Window)
        rect_size = QSize(int(50 * dpr), int(50 * dpr))
        left = top = right = bottom = int(radius * dpr)
        # Size of the pixmap.
        pixmap_size = QSize(rect_size.width() + left + right,
                            rect_size.height() + top + bottom)
        shadow_rect = QRect(QPoint(left, top) - offset * dpr, rect_size)
        pixmap = QPixmap(pixmap_size)
        pixmap.fill(Qt.transparent)

        pixmap = render_drop_shadow_frame(
            pixmap,
            QRectF(shadow_rect),
            shadow_color=color,
            offset=QPointF(offset * dpr),
            radius=radius * dpr,
            rect_fill_color=fill_color
        )
        pixmap.setDevicePixelRatio(dpr)
        return pixmap
예제 #9
0
def decorate_welcome_icon(icon, background_color):
    """Return a `QIcon` with a circle shaped background.
    """
    welcome_icon = QIcon()
    sizes = [32, 48, 64, 80]
    background_color = NAMED_COLORS.get(background_color, background_color)
    background_color = QColor(background_color)
    grad = radial_gradient(background_color)
    for size in sizes:
        icon_pixmap = icon.pixmap(5 * size / 8, 5 * size / 8)
        icon_size = icon_pixmap.size()
        icon_rect = QRect(QPoint(0, 0), icon_size)

        pixmap = QPixmap(size, size)
        pixmap.fill(QColor(0, 0, 0, 0))
        p = QPainter(pixmap)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.setBrush(QBrush(grad))
        p.setPen(Qt.NoPen)
        ellipse_rect = QRect(0, 0, size, size)
        p.drawEllipse(ellipse_rect)
        icon_rect.moveCenter(ellipse_rect.center())
        p.drawPixmap(icon_rect.topLeft(), icon_pixmap)
        p.end()

        welcome_icon.addPixmap(pixmap)

    return welcome_icon
예제 #10
0
def decorate_welcome_icon(icon, background_color):
    # type: (QIcon, Union[QColor, str]) -> QIcon
    """Return a `QIcon` with a circle shaped background.
    """
    welcome_icon = QIcon()
    sizes = [32, 48, 64, 80, 128, 256]
    background_color = NAMED_COLORS.get(background_color, background_color)
    background_color = QColor(background_color)
    grad = radial_gradient(background_color)
    for size in sizes:
        icon_size = QSize(int(5 * size / 8), int(5 * size / 8))
        icon_rect = QRect(QPoint(0, 0), icon_size)
        pixmap = QPixmap(size, size)
        pixmap.fill(Qt.transparent)
        p = QPainter(pixmap)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.setBrush(QBrush(grad))
        p.setPen(Qt.NoPen)
        ellipse_rect = QRect(0, 0, size, size)
        p.drawEllipse(ellipse_rect)
        icon_rect.moveCenter(ellipse_rect.center())
        icon.paint(
            p,
            icon_rect,
            Qt.AlignCenter,
        )
        p.end()

        welcome_icon.addPixmap(pixmap)

    return welcome_icon
예제 #11
0
def palette_pixmap(colors, size):
    img = QPixmap(size)
    img.fill(Qt.transparent)

    painter = QPainter(img)
    grad = palette_gradient(colors)
    grad.setCoordinateMode(QLinearGradient.ObjectBoundingMode)
    painter.setPen(Qt.NoPen)
    painter.setBrush(QBrush(grad))
    painter.drawRect(0, 0, size.width(), size.height())
    painter.end()
    return img
예제 #12
0
def palette_pixmap(colors, size):
    img = QPixmap(size)
    img.fill(Qt.transparent)

    painter = QPainter(img)
    grad = palette_gradient(colors)
    grad.setCoordinateMode(QLinearGradient.ObjectBoundingMode)
    painter.setPen(Qt.NoPen)
    painter.setBrush(QBrush(grad))
    painter.drawRect(0, 0, size.width(), size.height())
    painter.end()
    return img
예제 #13
0
 def update_legend(self, colors, labels):
     layout = self.legend.layout()
     while self.legend_items:
         w = self.legend_items.pop()
         layout.removeWidget(w)
         w.deleteLater()
     for row, (color, label) in enumerate(zip(colors, labels)):
         icon = QLabel()
         p = QPixmap(12, 12)
         p.fill(color)
         icon.setPixmap(p)
         label = QLabel(label)
         layout.addWidget(icon, row, 0)
         layout.addWidget(label, row, 1, alignment=Qt.AlignLeft)
         self.legend_items += (icon, label)
예제 #14
0
 def update_legend(self, colors, labels):
     layout = self.legend.layout()
     while self.legend_items:
         w = self.legend_items.pop()
         layout.removeWidget(w)
         w.deleteLater()
     for row, (color, label) in enumerate(zip(colors, labels)):
         icon = QLabel()
         p = QPixmap(12, 12)
         p.fill(color)
         icon.setPixmap(p)
         label = QLabel(label)
         layout.addWidget(icon, row, 0)
         layout.addWidget(label, row, 1, alignment=Qt.AlignLeft)
         self.legend_items += (icon, label)
예제 #15
0
def crosshairs(color, radius=24, circle=False):
    radius = max(radius, 16)
    pixmap = QPixmap(radius, radius)
    pixmap.fill(Qt.transparent)
    painter = QPainter()
    painter.begin(pixmap)
    painter.setRenderHints(QPainter.Antialiasing)
    pen = QPen(QBrush(color), 1)
    pen.setWidthF(1.5)
    painter.setPen(pen)
    if circle:
        painter.drawEllipse(2, 2, radius - 2, radius - 2)
    painter.drawLine(radius / 2, 7, radius / 2, radius / 2 - 7)
    painter.drawLine(7, radius / 2, radius / 2 - 7, radius / 2)
    painter.end()
    return pixmap
        def init_combos():
            """
            function initialize the combos with attributes
            """
            reset_combos()

            c_vars = [var for var in data.domain.variables if var.is_continuous]

            self.x_var_model[:] = c_vars
            self.y_var_model[:] = c_vars

            for i, var in enumerate(data.domain.class_var.values):
                pix_map = QPixmap(60, 60)
                color = tuple(data.domain.class_var.colors[i].tolist())
                pix_map.fill(QColor(*color))
                self.target_class_combobox.addItem(QIcon(pix_map), var)
예제 #17
0
def crosshairs(color, radius=24, circle=False):
    radius = max(radius, 16)
    pixmap = QPixmap(radius, radius)
    pixmap.fill(Qt.transparent)
    painter = QPainter()
    painter.begin(pixmap)
    painter.setRenderHints(QPainter.Antialiasing)
    pen = QPen(QBrush(color), 1)
    pen.setWidthF(1.5)
    painter.setPen(pen)
    if circle:
        painter.drawEllipse(2, 2, radius - 2, radius - 2)
    painter.drawLine(radius / 2, 7, radius / 2, radius / 2 - 7)
    painter.drawLine(7, radius / 2, radius / 2 - 7, radius / 2)
    painter.end()
    return pixmap
        def init_combos():
            """
            function initialize the combos with attributes
            """
            reset_combos()

            c_vars = [var for var in data.domain.variables if var.is_continuous]

            self.x_var_model[:] = c_vars
            self.y_var_model[:] = c_vars

            for i, var in enumerate(data.domain.class_var.values):
                pix_map = QPixmap(60, 60)
                color = tuple(data.domain.class_var.colors[i].tolist())
                pix_map.fill(QColor(*color))
                self.target_class_combobox.addItem(QIcon(pix_map), var)
예제 #19
0
    def setHistogram(self,
                     values=None,
                     bins=None,
                     use_kde=False,
                     histogram=None):
        """ Set background histogram (or density estimation, violin plot)

        The histogram of bins is calculated from values, optionally as a
        Gaussian KDE. If histogram is provided, its values are used directly
        and other parameters are ignored.
        """
        if (values is None or not len(values)) and histogram is None:
            self.setPixmap(None)
            return
        if histogram is not None:
            self._histogram = hist = histogram
        else:
            if bins is None:
                bins = min(100, max(10, len(values) // 20))
            if use_kde:
                hist = gaussian_kde(
                    values, None if isinstance(use_kde, bool) else use_kde)(
                        np.linspace(np.min(values), np.max(values), bins))
            else:
                hist = np.histogram(values, bins)[0]
            self._histogram = hist = hist / hist.max()

        HEIGHT = self.rect().height() / 2
        OFFSET = HEIGHT * .3
        pixmap = QPixmap(QSize(
            len(hist), 2 *
            (HEIGHT + OFFSET)))  # +1 avoids right/bottom frame border shadow
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        painter.setPen(QPen(Qt.darkGray))
        for x, value in enumerate(hist):
            painter.drawLine(x,
                             HEIGHT * (1 - value) + OFFSET, x,
                             HEIGHT * (1 + value) + OFFSET)

        if self.orientation() != Qt.Horizontal:
            pixmap = pixmap.transformed(QTransform().rotate(-90))

        self.setPixmap(pixmap)
예제 #20
0
    def __startInternalDrag(self, frame, hotSpot=None):
        drag = QDrag(self)
        pixmap = QPixmap(frame.size())
        frame.render(pixmap)

        transparent = QPixmap(pixmap.size())
        transparent.fill(Qt.transparent)
        painter = QPainter(transparent)
        painter.setOpacity(0.35)
        painter.drawPixmap(0, 0, pixmap.width(), pixmap.height(), pixmap)
        painter.end()

        drag.setPixmap(transparent)
        if hotSpot is not None:
            drag.setHotSpot(hotSpot)
        mime = QMimeData()
        mime.setData("application/x-internal-move", b"")
        drag.setMimeData(mime)
        return drag.exec(Qt.MoveAction)
예제 #21
0
    def __startInternalDrag(self, frame, hotSpot=None):
        drag = QDrag(self)
        pixmap = QPixmap(frame.size())
        frame.render(pixmap)

        transparent = QPixmap(pixmap.size())
        transparent.fill(Qt.transparent)
        painter = QPainter(transparent)
        painter.setOpacity(0.35)
        painter.drawPixmap(0, 0, pixmap.width(), pixmap.height(), pixmap)
        painter.end()

        drag.setPixmap(transparent)
        if hotSpot is not None:
            drag.setHotSpot(hotSpot)
        mime = QMimeData()
        mime.setData("application/x-internal-move", b"")
        drag.setMimeData(mime)
        return drag.exec_(Qt.MoveAction)
        def init_combos():
            """
            function initialize the combos with attributes
            """
            reset_combos()

            c_vars = [var for var in d.domain.attributes if var.is_continuous]

            self.x_var_model[:] = c_vars
            self.y_var_model[:] = c_vars if self.is_logistic else []

            for i, var in (enumerate(d.domain.class_var.values)
                           if d.domain.class_var.is_discrete else []):
                pix_map = QPixmap(60, 60)
                color = tuple(d.domain.class_var.colors[i].tolist())
                pix_map.fill(QColor(*color))
                self.target_class_combobox.addItem(QIcon(pix_map), var)

            self.cby.setDisabled(not self.is_logistic)
            self.target_class_combobox.setDisabled(not self.is_logistic)
예제 #23
0
        def init_combos():
            """
            function initialize the combos with attributes
            """
            reset_combos()

            c_vars = [var for var in d.domain.attributes if var.is_continuous]

            self.x_var_model[:] = c_vars
            self.y_var_model[:] = c_vars if self.is_logistic else []

            for i, var in (enumerate(d.domain.class_var.values)
                           if d.domain.class_var.is_discrete else []):
                pix_map = QPixmap(60, 60)
                color = tuple(d.domain.class_var.colors[i].tolist())
                pix_map.fill(QColor(*color))
                self.target_class_combobox.addItem(QIcon(pix_map), var)

            self.cby.setDisabled(not self.is_logistic)
            self.target_class_combobox.setDisabled(not self.is_logistic)
예제 #24
0
    def _updateShadowPixmap(self):
        """Update the cached drop shadow pixmap.
        """
        # Rectangle casting the shadow
        rect_size = QSize(*CACHED_SHADOW_RECT_SIZE)
        left, top, right, bottom = self.getContentsMargins()
        # Size of the pixmap.
        pixmap_size = QSize(rect_size.width() + left + right,
                            rect_size.height() + top + bottom)
        shadow_rect = QRect(QPoint(left, top), rect_size)
        pixmap = QPixmap(pixmap_size)
        pixmap.fill(QColor(0, 0, 0, 0))
        rect_fill_color = self.palette().color(QPalette.Window)

        pixmap = render_drop_shadow_frame(pixmap, QRectF(shadow_rect),
                                          shadow_color=self.color,
                                          offset=self.offset,
                                          radius=self.radius,
                                          rect_fill_color=rect_fill_color)

        self._shadowPixmap = pixmap
예제 #25
0
    def _updateShadowPixmap(self):
        """Update the cached drop shadow pixmap.
        """
        # Rectangle casting the shadow
        rect_size = QSize(*CACHED_SHADOW_RECT_SIZE)
        left, top, right, bottom = self.getContentsMargins()
        # Size of the pixmap.
        pixmap_size = QSize(rect_size.width() + left + right,
                            rect_size.height() + top + bottom)
        shadow_rect = QRect(QPoint(left, top), rect_size)
        pixmap = QPixmap(pixmap_size)
        pixmap.fill(QColor(0, 0, 0, 0))
        rect_fill_color = self.palette().color(QPalette.Window)

        pixmap = render_drop_shadow_frame(pixmap, QRectF(shadow_rect),
                                          shadow_color=self.color,
                                          offset=self.offset,
                                          radius=self.radius,
                                          rect_fill_color=rect_fill_color)

        self._shadowPixmap = pixmap
예제 #26
0
    def pixmap(self, size, mode, state):
        # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap
        if not self.__generator.isValid():
            return QPixmap()

        dsize = self.__generator.defaultSize()  # type: QSize
        if not dsize.isNull():
            dsize.scale(size, Qt.KeepAspectRatio)
            size = dsize

        pm = QPixmap(size)
        pm.fill(Qt.transparent)
        painter = QPainter(pm)
        try:
            self.__generator.render(painter, QRectF(0, 0, size.width(), size.height()))
        finally:
            painter.end()
        style = QApplication.style()
        if style is not None:
            opt = QStyleOption()
            opt.palette = QApplication.palette()
            pm = style.generatedIconPixmap(mode, pm, opt)
        return pm
예제 #27
0
    def setHistogram(self, values=None, bins=None, use_kde=False, histogram=None):
        """ Set background histogram (or density estimation, violin plot)

        The histogram of bins is calculated from values, optionally as a
        Gaussian KDE. If histogram is provided, its values are used directly
        and other parameters are ignored.
        """
        if (values is None or not len(values)) and histogram is None:
            self.setPixmap(None)
            return
        if histogram is not None:
            self._histogram = hist = histogram
        else:
            if bins is None:
                bins = min(100, max(10, len(values) // 20))
            if use_kde:
                hist = gaussian_kde(values,
                                    None if isinstance(use_kde, bool) else use_kde)(
                    np.linspace(np.min(values), np.max(values), bins))
            else:
                hist = np.histogram(values, bins)[0]
            self._histogram = hist = hist / hist.max()

        HEIGHT = self.rect().height() / 2
        OFFSET = HEIGHT * .3
        pixmap = QPixmap(QSize(len(hist), 2 * (HEIGHT + OFFSET)))  # +1 avoids right/bottom frame border shadow
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        painter.setPen(QPen(Qt.darkGray))
        for x, value in enumerate(hist):
            painter.drawLine(x, HEIGHT * (1 - value) + OFFSET,
                             x, HEIGHT * (1 + value) + OFFSET)

        if self.orientation() != Qt.Horizontal:
            pixmap = pixmap.transformed(QTransform().rotate(-90))

        self.setPixmap(pixmap)
예제 #28
0
    def pixmap(self, size, mode, state):
        # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap
        if not self.__generator.isValid():
            return QPixmap()

        dsize = self.__generator.defaultSize()  # type: QSize
        if not dsize.isNull():
            dsize.scale(size, Qt.KeepAspectRatio)
            size = dsize

        pm = QPixmap(size)
        pm.fill(Qt.transparent)
        painter = QPainter(pm)
        try:
            self.__generator.render(
                painter, QRectF(0, 0, size.width(), size.height()))
        finally:
            painter.end()
        style = QApplication.style()
        if style is not None:
            opt = QStyleOption()
            opt.palette = QApplication.palette()
            pm = style.generatedIconPixmap(mode, pm, opt)
        return pm
예제 #29
0
    def __preview_color(self):
        """
		Shows selected colors in two QLabel widgets.

		The first shows true color, while the second presents the color
		with an opacity as seen in the timeline and with some dummy text
		to preview readability.
		"""
        pixmap = QPixmap(50, 25)
        color = QColor(*self.color.getRgb())

        # Preview color
        color.setAlpha(int(255 * 1.0))
        pixmap.fill(color)
        self._ui.label_color.setPixmap(pixmap)

        # Preview color with transparency and some text
        color.setAlpha(int(255 * 0.5))
        pixmap.fill(color)
        painter = QPainter(pixmap)
        painter.setFont(QFont('Decorative', 8))
        painter.drawText(pixmap.rect(), QtCore.Qt.AlignCenter, "Text")
        painter.end()
        self._ui.label_color_alpha.setPixmap(pixmap)
예제 #30
0
def innerShadowPixmap(color, size, pos, length=5):
    """
    Args:
        color (QColor): shadow color
        size (QSize): size of pixmap
        pos (int): shadow position int flag, use bitwise operations
            1 - top
            2 - right
            4 - bottom
            8 - left
        length (int): length of cast shadow
    """
    key = "InnerShadow " + \
          color.name() + " " + \
          str(size) + " " + \
          str(pos) + " " + \
          str(length)
    # get cached shadow if it exists
    finalShadow = QPixmapCache.find(key)
    if finalShadow:
        return finalShadow

    shadowTemplate = shadowTemplatePixmap(color, length)

    finalShadow = QPixmap(size)
    finalShadow.fill(Qt.transparent)
    shadowPainter = QPainter(finalShadow)
    shadowPainter.setCompositionMode(QPainter.CompositionMode_Darken)

    # top/bottom rect
    targetRect = QRect(0, 0, size.width(), length)

    # shadow on top
    if pos & 1:
        shadowPainter.drawPixmap(targetRect, shadowTemplate, shadowTemplate.rect())
    # shadow on bottom
    if pos & 4:
        shadowPainter.save()

        shadowPainter.translate(QPointF(0, size.height()))
        shadowPainter.scale(1, -1)
        shadowPainter.drawPixmap(targetRect, shadowTemplate, shadowTemplate.rect())

        shadowPainter.restore()

    # left/right rect
    targetRect = QRect(0, 0, size.height(), shadowTemplate.rect().height())

    # shadow on the right
    if pos & 2:
        shadowPainter.save()

        shadowPainter.translate(QPointF(size.width(), 0))
        shadowPainter.rotate(90)
        shadowPainter.drawPixmap(targetRect, shadowTemplate, shadowTemplate.rect())

        shadowPainter.restore()
    # shadow on left
    if pos & 8:
        shadowPainter.save()

        shadowPainter.translate(0, size.height())
        shadowPainter.rotate(-90)
        shadowPainter.drawPixmap(targetRect, shadowTemplate, shadowTemplate.rect())

        shadowPainter.restore()

    shadowPainter.end()

    # cache shadow
    QPixmapCache.insert(key, finalShadow)

    return finalShadow
예제 #31
0
def init_style_option(
        delegate: QStyledItemDelegate,
        option: QStyleOptionViewItem,
        index: QModelIndex,
        data: Mapping[int, Any],
        roles: Optional[Container[int]] = None,
) -> None:
    """
    Like `QStyledItemDelegate.initStyleOption` but fill in the fields from
    `data` mapping. If `roles` is not `None` init the `option` for the
    specified `roles` only.
    """
    # pylint: disable=too-many-branches
    option.styleObject = None
    option.index = index
    if roles is None:
        roles = data
    features = 0
    if Qt.DisplayRole in roles:
        value = data.get(Qt.DisplayRole)
        if value is not None:
            option.text = delegate.displayText(value, option.locale)
            features |= _QStyleOptionViewItem_HasDisplay
    if Qt.FontRole in roles:
        value = data.get(Qt.FontRole)
        font = cast_(QFont, value)
        if font is not None:
            font = font.resolve(option.font)
            option.font = font
            option.fontMetrics = QFontMetrics(option.font)
    if Qt.ForegroundRole in roles:
        value = data.get(Qt.ForegroundRole)
        foreground = cast_(QBrush, value)
        if foreground is not None:
            option.palette.setBrush(QPalette.Text, foreground)
    if Qt.BackgroundRole in roles:
        value = data.get(Qt.BackgroundRole)
        background = cast_(QBrush, value)
        if background is not None:
            option.backgroundBrush = background
    if Qt.TextAlignmentRole in roles:
        value = data.get(Qt.TextAlignmentRole)
        alignment = cast_(int, value)
        if alignment is not None:
            alignment = alignment & _AlignmentMask
            option.displayAlignment = _AlignmentCache[alignment]
    if Qt.CheckStateRole in roles:
        state = data.get(Qt.CheckStateRole)
        if state is not None:
            features |= _QStyleOptionViewItem_HasCheckIndicator
            state = cast_(int, state)
            if state is not None:
                option.checkState = state
    if Qt.DecorationRole in roles:
        value = data.get(Qt.DecorationRole)
        if value is not None:
            features |= _QStyleOptionViewItem_HasDecoration
        if isinstance(value, QIcon):
            option.icon = value
        elif isinstance(value, QColor):
            pix = QPixmap(option.decorationSize)
            pix.fill(value)
            option.icon = QIcon(pix)
        elif isinstance(value, QPixmap):
            option.icon = QIcon(value)
            option.decorationSize = (value.size() / value.devicePixelRatio()).toSize()
        elif isinstance(value, QImage):
            pix = QPixmap.fromImage(value)
            option.icon = QIcon(value)
            option.decorationSize = (pix.size() / pix.devicePixelRatio()).toSize()
    option.features |= features
예제 #32
0
def innerGlowBackgroundPixmap(color, size, radius=5):
    """ Draws radial gradient pixmap, then uses that to draw
    a rounded-corner gradient rectangle pixmap.

    Args:
        color (QColor): used as outer color (lightness 245 used for inner)
        size (QSize): size of output pixmap
        radius (int): radius of inner glow rounded corners
    """
    key = "InnerGlowBackground " + \
          color.name() + " " + \
          str(radius)

    bg = QPixmapCache.find(key)
    if bg:
        return bg

    # set background colors for gradient
    color = color.toHsl()
    light_color = color.fromHsl(color.hslHue(), color.hslSaturation(), 245)
    dark_color = color

    # initialize radial gradient
    center = QPoint(radius, radius)
    pixRect = QRect(0, 0, radius * 2, radius * 2)
    gradientPixmap = QPixmap(radius * 2, radius * 2)
    gradientPixmap.fill(dark_color)

    # draw radial gradient pixmap
    pixPainter = QPainter(gradientPixmap)
    pixPainter.setPen(Qt.NoPen)
    gradient = QRadialGradient(center, radius - 1)
    gradient.setColorAt(0, light_color)
    gradient.setColorAt(1, dark_color)
    pixPainter.setBrush(gradient)
    pixPainter.drawRect(pixRect)
    pixPainter.end()

    # set tl and br to the gradient's square-shaped rect
    tl = QPoint(0, 0)
    br = QPoint(size.width(), size.height())

    # fragments of radial gradient pixmap to create rounded gradient outline rectangle
    frags = [
        # top-left corner
        QPainter.PixmapFragment.create(
            QPointF(tl.x() + radius / 2, tl.y() + radius / 2),
            QRectF(0, 0, radius, radius)
        ),
        # top-mid 'linear gradient'
        QPainter.PixmapFragment.create(
            QPointF(tl.x() + (br.x() - tl.x()) / 2, tl.y() + radius / 2),
            QRectF(radius, 0, 1, radius),
            scaleX=(br.x() - tl.x() - 2 * radius)
        ),
        # top-right corner
        QPainter.PixmapFragment.create(
            QPointF(br.x() - radius / 2, tl.y() + radius / 2),
            QRectF(radius, 0, radius, radius)
        ),
        # left-mid 'linear gradient'
        QPainter.PixmapFragment.create(
            QPointF(tl.x() + radius / 2, tl.y() + (br.y() - tl.y()) / 2),
            QRectF(0, radius, radius, 1),
            scaleY=(br.y() - tl.y() - 2 * radius)
        ),
        # mid solid
        QPainter.PixmapFragment.create(
            QPointF(tl.x() + (br.x() - tl.x()) / 2, tl.y() + (br.y() - tl.y()) / 2),
            QRectF(radius, radius, 1, 1),
            scaleX=(br.x() - tl.x() - 2 * radius),
            scaleY=(br.y() - tl.y() - 2 * radius)
        ),
        # right-mid 'linear gradient'
        QPainter.PixmapFragment.create(
            QPointF(br.x() - radius / 2, tl.y() + (br.y() - tl.y()) / 2),
            QRectF(radius, radius, radius, 1),
            scaleY=(br.y() - tl.y() - 2 * radius)
        ),
        # bottom-left corner
        QPainter.PixmapFragment.create(
            QPointF(tl.x() + radius / 2, br.y() - radius / 2),
            QRectF(0, radius, radius, radius)
        ),
        # bottom-mid 'linear gradient'
        QPainter.PixmapFragment.create(
            QPointF(tl.x() + (br.x() - tl.x()) / 2, br.y() - radius / 2),
            QRectF(radius, radius, 1, radius),
            scaleX=(br.x() - tl.x() - 2 * radius)
        ),
        # bottom-right corner
        QPainter.PixmapFragment.create(
            QPointF(br.x() - radius / 2, br.y() - radius / 2),
            QRectF(radius, radius, radius, radius)
        ),
    ]

    # draw icon background to pixmap
    outPix = QPixmap(size.width(), size.height())
    outPainter = QPainter(outPix)
    outPainter.setPen(Qt.NoPen)
    outPainter.drawPixmapFragments(frags,
                                   gradientPixmap,
                                   QPainter.PixmapFragmentHints(QPainter.OpaqueHint))
    outPainter.end()

    QPixmapCache.insert(key, outPix)

    return outPix
예제 #33
0
 def __init__(self, color=QColor(Qt.white), size=12):
     p = QPixmap(size, size)
     p.fill(color)
     self.color = color
     QIcon.__init__(self, p)
예제 #34
0
 def basic_icon():
     pixmap = QPixmap(15, 15)
     pixmap.fill(QColor("red"))
     return QIcon(pixmap)
예제 #35
0
 def __init__(self, color=QColor(Qt.white), size=12):
     p = QPixmap(size, size)
     p.fill(color)
     self.color = color
     QIcon.__init__(self, p)