Python qtpy.QtGui.QColor() Examples

The following are 30 code examples of qtpy.QtGui.QColor(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module qtpy.QtGui , or try the search function .
Example #1
Source File: port.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mouseMoveEvent(self, event):
        self.unhighlight()
        scenePos = self.mapToScene(event.pos())

        # When clicking on an UI port label, it is ambigous which connection point should be activated.
        # We let the user drag the mouse in either direction to select the conneciton point to activate.
        delta = scenePos - self.__mousDownPos
        if delta.x() < 0:
            if self.__port.inCircle() is not None:
                self.__port.inCircle().mousePressEvent(event)
        else:
            if self.__port.outCircle() is not None:
                self.__port.outCircle().mousePressEvent(event)

    # def paint(self, painter, option, widget):
    #     super(PortLabel, self).paint(painter, option, widget)
    #     painter.setPen(QtGui.QPen(QtGui.QColor(0, 0, 255)))
    #     painter.drawRect(self.windowFrameRect()) 
Example #2
Source File: port.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mousePressEvent(self, event):

        self.unhighlight()

        scenePos = self.mapToScene(event.pos())

        from .mouse_grabber import MouseGrabber
        if self.isInConnectionPoint():
            MouseGrabber(self._graph, scenePos, self, 'Out')
        elif self.isOutConnectionPoint():
            MouseGrabber(self._graph, scenePos, self, 'In')


    # def paint(self, painter, option, widget):
    #     super(PortCircle, self).paint(painter, option, widget)
    #     painter.setPen(QtGui.QPen(QtGui.QColor(255, 255, 0)))
    #     painter.drawRect(self.windowFrameRect()) 
Example #3
Source File: bracket_matcher.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, text_edit):
        """ Create a call tip manager that is attached to the specified Qt
            text edit widget.
        """
        assert isinstance(text_edit, (QtWidgets.QTextEdit, QtWidgets.QPlainTextEdit))
        super(BracketMatcher, self).__init__()

        # The format to apply to matching brackets.
        self.format = QtGui.QTextCharFormat()
        self.format.setBackground(QtGui.QColor('silver'))

        self._text_edit = text_edit
        text_edit.cursorPositionChanged.connect(self._cursor_position_changed)

    #--------------------------------------------------------------------------
    # Protected interface
    #-------------------------------------------------------------------------- 
Example #4
Source File: qt_color_dialog.py    From napari with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(
        self, parent: QWidget = None, initial_color: AnyColorType = None
    ) -> None:
        super().__init__(parent)
        self.setObjectName('QtColorPopup')
        self.color_dialog = CustomColorDialog(self)

        # native dialog doesn't get added to the QtPopup frame
        # so more would need to be done to use it
        self.color_dialog.setOptions(
            QColorDialog.DontUseNativeDialog | QColorDialog.ShowAlphaChannel
        )
        layout = QVBoxLayout()
        self.frame.setLayout(layout)
        layout.addWidget(self.color_dialog)

        self.color_dialog.currentColorChanged.connect(
            self.currentColorChanged.emit
        )
        self.color_dialog.colorSelected.connect(self._on_color_selected)
        self.color_dialog.rejected.connect(self._on_rejected)
        self.color_dialog.setCurrentColor(QColor(initial_color)) 
Example #5
Source File: qt_color_dialog.py    From napari with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setColor(self, color: AnyColorType) -> None:
        """Set the color of the swatch.

        Parameters
        ----------
        color : ColorType
            Can be any ColorType recognized by our
            utils.colormaps.standardize_color.transform_color function.
        """
        if isinstance(color, QColor):
            _color = (np.array(color.getRgb()) / 255).astype(np.float32)
        else:
            try:
                _color = transform_color(color)[0]
            except ValueError:
                return self.color_changed.emit(self._color)
        emit = np.any(self._color != _color)
        self._color = _color
        if emit or np.all(_color == TRANSPARENT):
            self.color_changed.emit(_color) 
Example #6
Source File: bigGraph.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generateNodes(count, offset, depth):
    for i in range(count):
        node1 = Node(graph, 'node' + str(depth) + str(i))
        node1.addPort(InputPort(node1, graph, 'InPort', QtGui.QColor(128, 170, 170, 255), 'MyDataX'))
        node1.addPort(OutputPort(node1, graph, 'OutPort', QtGui.QColor(32, 255, 32, 255), 'MyDataX'))
        node1.setGraphPos(QtCore.QPointF(offset, i * 80 ))

        graph.addNode(node1)

        global totalCount
        totalCount += 1

    if depth < 6:
        generateNodes( count * 2, offset+160, depth+1)

        for i in range(count):
            graph.connectPorts('node' + str(depth) + str(i), 'OutPort', 'node' + str(depth+1) + str(i*2), 'InPort')
            graph.connectPorts('node' + str(depth) + str(i), 'OutPort', 'node' + str(depth+1) + str(i*2+1), 'InPort')
    elif depth < 12:
        generateNodes( int(count / 2), offset+160, depth+1)

        for i in range(count//2):
            graph.connectPorts('node' + str(depth) + str(i), 'OutPort', 'node' + str(depth+1) + str(int(i)), 'InPort') 
Example #7
Source File: logger_tab.py    From cutelog with MIT License 6 votes vote down vote up
def data_internal(self, index, record, role):
        result = None
        if role == Qt.DisplayRole:
            if index.column() == self.columnCount(INVALID_INDEX) - 1:
                result = record._cutelog
            else:
                column = self.table_header[index.column()]
                if column.name == 'asctime':
                    result = record.asctime
        elif role == Qt.SizeHintRole:
            result = QSize(1, CONFIG.logger_row_height)
        elif role == Qt.FontRole:
            result = QFont(CONFIG.logger_table_font, CONFIG.logger_table_font_size)
        elif role == Qt.ForegroundRole:
            if not self.dark_theme:
                result = QColor(Qt.black)
            else:
                result = QColor(Qt.white)
        elif role == Qt.BackgroundRole:
            if not self.dark_theme:
                color = QColor(Qt.lightGray)
            else:
                color = QColor(Qt.darkGray)
            result = QBrush(color, Qt.BDiagPattern)
        return result 
Example #8
Source File: QtShortCuts.py    From pylustrator with GNU General Public License v3.0 6 votes vote down vote up
def openDialog(self):
        """ open a color choosed dialog """
        if self.color in self.maps:
            dialog = ColorMapChoose(self.parent(), self.color)
            colormap, selected = dialog.exec()
            if selected is False:
                return
            self.setColor(colormap)
        else:
            # get new color from color picker
            qcolor = QtGui.QColor(*np.array(mpl.colors.to_rgb(self.getColor())) * 255)
            color = QtWidgets.QColorDialog.getColor(qcolor, self.parent())
            # if a color is set, apply it
            if color.isValid():
                color = "#%02x%02x%02x" % color.getRgb()[:3]
                self.setColor(color) 
Example #9
Source File: wdifftreeview.py    From pyCGNS with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, owner, model, diag):
        QStyledItemDelegate.__init__(self, owner)
        self._parent = owner
        self._model = model
        self._diag = diag
        self.orange = QColor("#FFA500")
        self.red = QColor("#FF0000")
        self.green = QColor("#008000")
        self.gray = QColor("#C0C0C0") 
Example #10
Source File: packages.py    From conda-manager with MIT License 5 votes vote down vote up
def __init__(self, parent, packages, data):
        super(CondaPackagesModel, self).__init__(parent)
        self._parent = parent
        self._packages = packages
        self._rows = data
        self._name_to_index = {r[C.COL_NAME]: i for i, r in enumerate(data)}

        palette = QPalette()
        self._palette = {
            'icon.upgrade.active': get_icon('conda_upgrade_active.png'),
            'icon.upgrade.inactive': get_icon('conda_upgrade_inactive.png'),
            'icon.upgrade.pressed': get_icon('conda_upgrade_pressed.png'),
            'icon.downgrade.active': get_icon('conda_downgrade_active.png'),
            'icon.downgrade.inactive': get_icon('conda_downgrade_inactive.png'),
            'icon.downgrade.pressed': get_icon('conda_downgrade_pressed.png'),
            'icon.add.active': get_icon('conda_add_active.png'),
            'icon.add.inactive': get_icon('conda_add_inactive.png'),
            'icon.add.pressed': get_icon('conda_add_pressed.png'),
            'icon.remove.active': get_icon('conda_remove_active.png'),
            'icon.remove.inactive': get_icon('conda_remove_inactive.png'),
            'icon.remove.pressed': get_icon('conda_remove_pressed.png'),
            'icon.action.not_installed': get_icon('conda_action_not_installed.png'),
            'icon.action.installed': get_icon('conda_action_installed.png'),
            'icon.action.installed_upgradable': get_icon('conda_action_installed_upgradable.png'),
            'icon.action.remove': get_icon('conda_action_remove.png'),
            'icon.action.add': get_icon('conda_action_add.png'),
            'icon.action.upgrade': get_icon('conda_action_upgrade.png'),
            'icon.action.downgrade': get_icon('conda_action_downgrade.png'),
            'icon.upgrade.arrow': get_icon('conda_upgrade_arrow.png'),
            'spacer': get_icon('spacer.png'),
            'icon.python': get_icon('python.png').pixmap(QSize(16, 16)),
            'icon.anaconda': get_icon('anaconda.png').pixmap(QSize(16, 16)),
            'background.remove': QColor(128, 0, 0, 50),
            'background.install': QColor(0, 128, 0, 50),
            'background.upgrade': QColor(0, 0, 128, 50),
            'background.downgrade': QColor(128, 0, 128, 50),
            'foreground.not.installed': palette.color(QPalette.Mid),
            'foreground.upgrade': QColor(0, 0, 128, 255),
            } 
Example #11
Source File: color.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def color_qt(name: str) -> QColor:
    """Get color and translate to QColor."""
    return QColor(*color_rgb(name)) 
Example #12
Source File: color.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def color_num(color_index: int) -> QColor:
    """Get color by index."""
    return color_qt(color_names[color_index % len(color_names)]) 
Example #13
Source File: color.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def target_path_style(color_index: int) -> Tuple[QColor, QColor]:
    """Get path colors."""
    return _path_color[color_index % len(_path_color)] 
Example #14
Source File: utility.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_custom_color(color_box: QComboBox, color: QColor):
    rgb_str = f"({color.red()}, {color.green()}, {color.blue()})"
    color_box.addItem(color_icon(rgb_str), rgb_str)
    color_box.setCurrentIndex(color_box.count() - 1) 
Example #15
Source File: canvas_base.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __draw_link(self, vlink: VLink) -> None:
        """Draw a link."""
        if vlink.name == VLink.FRAME or not vlink.points:
            return
        pen = QPen()
        # Rearrange: Put the nearest point to the next position.
        qpoints = convex_hull(
            [(c.x * self.zoom, c.y * -self.zoom)
             for c in vlink.points_pos(self.vpoints)], as_qpoint=True)
        if (
            self.select_mode == SelectMode.LINK
            and self.vlinks.index(vlink) in self.selections
        ):
            pen.setWidth(self.link_width + 6)
            pen.setColor(Qt.black if self.monochrome else QColor(161, 16, 239))
            self.painter.setPen(pen)
            self.painter.drawPolygon(*qpoints)
        pen.setWidth(self.link_width)
        pen.setColor(Qt.black if self.monochrome else QColor(*vlink.color))
        self.painter.setPen(pen)
        self.painter.drawPolygon(*qpoints)
        if not self.show_point_mark:
            return
        pen.setColor(Qt.darkGray)
        self.painter.setPen(pen)
        p_count = len(qpoints)
        cen_x = sum(p.x() for p in qpoints) / p_count
        cen_y = sum(p.y() for p in qpoints) / p_count
        self.painter.drawText(
            QRectF(cen_x - 50, cen_y - 50, 100, 100),
            Qt.AlignCenter,
            f'[{vlink.name}]'
        ) 
Example #16
Source File: restart.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def _show_message(self, text):
        """Show message on splash screen."""
        self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter |
                                Qt.AlignAbsolute, QColor(Qt.black)) 
Example #17
Source File: mainwindow.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def set_splash(self, message):
        """Set splash message"""
        if self.splash is None:
            return
        if message:
            self.debug_print(message)
        self.splash.show()
        self.splash.showMessage(message, Qt.AlignBottom | Qt.AlignCenter |
                                Qt.AlignAbsolute, QColor(Qt.black))
        QApplication.processEvents() 
Example #18
Source File: restart.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def _show_message(self, text):
        """Show message on splash screen."""
        self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter |
                                Qt.AlignAbsolute, QColor(Qt.black)) 
Example #19
Source File: mainwindow.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def set_splash(self, message):
        """Set splash message"""
        if self.splash is None:
            return
        if message:
            self.debug_print(message)
        self.splash.show()
        self.splash.showMessage(message, Qt.AlignBottom | Qt.AlignCenter |
                                Qt.AlignAbsolute, QColor(Qt.black))
        QApplication.processEvents() 
Example #20
Source File: ansi_code_processor.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_color(self, color, intensity=0):
        """ Returns a QColor for a given color code or rgb list, or None if one
            cannot be constructed.
        """

        if isinstance(color, int):
            # Adjust for intensity, if possible.
            if color < 8 and intensity > 0:
                color += 8
            constructor = self.color_map.get(color, None)
        elif isinstance(color, (tuple, list)):
            constructor = color
        else:
            return None

        if isinstance(constructor, string_types):
            # If this is an X11 color name, we just hope there is a close SVG
            # color name. We could use QColor's static method
            # 'setAllowX11ColorNames()', but this is global and only available
            # on X11. It seems cleaner to aim for uniformity of behavior.
            return QtGui.QColor(constructor)

        elif isinstance(constructor, (tuple, list)):
            return QtGui.QColor(*constructor)

        return None 
Example #21
Source File: pygments_highlighter.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_color(self, color):
        """ Returns a QColor built from a Pygments color string.
        """
        qcolor = QtGui.QColor()
        qcolor.setRgb(int(color[:2], base=16),
                      int(color[2:4], base=16),
                      int(color[4:6], base=16))
        return qcolor 
Example #22
Source File: connection.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, graph, srcPortCircle, dstPortCircle):
        super(Connection, self).__init__()

        self.__graph = graph
        self.__srcPortCircle = srcPortCircle
        self.__dstPortCircle = dstPortCircle
        penStyle = QtCore.Qt.DashLine

        self.__connectionColor = QtGui.QColor(0, 0, 0)
        self.__connectionColor.setRgbF(*self.__srcPortCircle.getColor().getRgbF())
        self.__connectionColor.setAlpha(125)

        self.__defaultPen = QtGui.QPen(self.__connectionColor, 1.5, style=penStyle)
        self.__defaultPen.setDashPattern([1, 2, 2, 1])

        self.__connectionHoverColor = QtGui.QColor(0, 0, 0)
        self.__connectionHoverColor.setRgbF(*self.__srcPortCircle.getColor().getRgbF())
        self.__connectionHoverColor.setAlpha(255)

        self.__hoverPen = QtGui.QPen(self.__connectionHoverColor, 1.5, style=penStyle)
        self.__hoverPen.setDashPattern([1, 2, 2, 1])

        self.setPen(self.__defaultPen)
        self.setZValue(-1)

        self.setAcceptHoverEvents(True)
        self.connect() 
Example #23
Source File: qt_color_dialog.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _on_color_selected(self, color: QColor):
        """When a color has beeen selected and the OK button clicked."""
        self.colorSelected.emit(color)
        self.close() 
Example #24
Source File: qt_color_dialog.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mouseReleaseEvent(self, event: QEvent):
        """Show QColorPopup picker when the user clicks on the swatch."""
        if event.button() == Qt.LeftButton:
            initial = QColor(*(255 * self._color).astype('int'))
            popup = QColorPopup(self, initial)
            popup.colorSelected.connect(self.setColor)
            popup.show_right_of_mouse() 
Example #25
Source File: qt_console.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _update_palette(self, palette, themed_stylesheet):
        """Update the napari GUI theme.

        Parameters
        ----------
        palette : dict of str: str
            Color palette with which to style the viewer.
            Property of napari.components.viewer_model.ViewerModel.
        themed_stylesheet : str
            Stylesheet that has already been themed with the current pallete.
        """
        self.style_sheet = themed_stylesheet
        self.syntax_style = palette['syntax_style']
        bracket_color = QColor(*str_to_rgb(palette['highlight']))
        self._bracket_matcher.format.setBackground(bracket_color) 
Example #26
Source File: QLinkableWidgets.py    From pylustrator with GNU General Public License v3.0 5 votes vote down vote up
def OpenDialog(self):
        """ open a color chooser dialog """
        # get new color from color picker
        self.current_color = QtGui.QColor(*tuple(mpl.colors.to_rgba_array(self.getColor())[0] * 255))
        self.dialog = QtWidgets.QColorDialog(self.current_color, self.parent())
        self.dialog.setOptions(QtWidgets.QColorDialog.ShowAlphaChannel)
        for index, color in enumerate(plt.rcParams['axes.prop_cycle'].by_key()['color']):
            self.dialog.setCustomColor(index, QtGui.QColor(color))
        self.dialog.open(self.dialog_finished)
        self.dialog.currentColorChanged.connect(self.dialog_changed)
        self.dialog.rejected.connect(self.dialog_rejected) 
Example #27
Source File: log_levels.py    From cutelog with MIT License 5 votes vote down vote up
def loads(self, string):
        self.__dict__ = json.loads(string)
        self.styles = set(self.styles)
        self.stylesDark = set(self.stylesDark)
        self.fg, self.fgDark = QColor(self.fg), QColor(self.fgDark)
        self.bg, self.bgDark = QColor(self.bg), QColor(self.bgDark)
        return self 
Example #28
Source File: log_levels.py    From cutelog with MIT License 5 votes vote down vote up
def __init__(self, levelname, enabled=True, fg=None, bg=None,
                 fgDark=None, bgDark=None, styles=set(), stylesDark=None, load=None):
        if load:
            self.loads(load)
            return

        self.levelname = levelname

        self.enabled = enabled
        self.styles = styles
        if not stylesDark:
            self.stylesDark = deepcopy(styles)
        else:
            self.stylesDark = stylesDark

        if not fg:
            self.fg = QColor(0, 0, 0)
        else:
            self.fg = fg
        if not bg:
            self.bg = QColor(255, 255, 255)
        else:
            self.bg = bg

        if not fgDark:
            self.fgDark = QColor(255, 255, 255)
        else:
            self.fgDark = fgDark
        if not bgDark:
            self.bgDark = QColor(0, 0, 0)
        else:
            self.bgDark = bgDark 
Example #29
Source File: node.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def paint(self, painter, option, widget):
        rect = self.windowFrameRect()
        painter.setBrush(self.__color)

        painter.setPen(QtGui.QPen(QtGui.QColor(0, 0, 0, 0), 0))

        roundingY = 10
        roundingX = 10

        painter.drawRoundedRect(rect, roundingX, roundingY)

        # Title BG
        titleHeight = self.__headerItem.size().height() - 3

        painter.setBrush(self.__color.darker(125))
        roundingY = rect.width() * roundingX / titleHeight
        painter.drawRoundedRect(0, 0, rect.width(), titleHeight, roundingX, roundingY, QtCore.Qt.AbsoluteSize)
        painter.drawRect(0, titleHeight * 0.5 + 2, rect.width(), titleHeight * 0.5)

        painter.setBrush(QtGui.QColor(0, 0, 0, 0))
        if self.__selected:
            painter.setPen(self.__selectedPen)
        else:
            painter.setPen(self.__unselectedPen)

        roundingY = 10
        roundingX = 10

        painter.drawRoundedRect(rect, roundingX, roundingY, QtCore.Qt.AbsoluteSize)


    #########################
    ## Events 
Example #30
Source File: node.py    From pyflowgraph with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def addPort(self, port, alignment):
        layout = self.layout()
        layout.addItem(port)
        layout.setAlignment(port, alignment)
        self.adjustSize()
        return port

    # def paint(self, painter, option, widget):
    #     super(PortList, self).paint(painter, option, widget)
    #     painter.setPen(QtGui.QPen(QtGui.QColor(255, 255, 0)))
    #     painter.drawRect(self.windowFrameRect())