Create a color bar with Python + Qt (PySide)

Since PySide's QColorDialog looks normal, I created my own color picker widget. Here, we will introduce the color bars. The good thing about Python & Qt is that even I, who has been in Python for 3 months, can make something like that.

I registered the source on GitHub. https://github.com/tokyo-noctambulist/colorpicker.git

(Updated on 2017/03/07) Changed the value passed by reference when specifying the color to copy

sample

image

In sample.py, the color bars of two hues are linked and the color bar of transparency is displayed separately.


Color bar type

You can select the type of color bar from hue, saturation, brightness, and transparency. I registered with PyPI. You can install it with pip etc.

type value
Hue BAR_TYPE_HUE = 0
saturation BAR_TYPE_SATURATION = 1
brightness BAR_TYPE_VALUE = 2
Transparency BAR_TYPE_ALPHA = 3

function


pip install colorpicker #install

from colorpicker import *

QColorBarWidget(parent,Types of BAR(=Hue when not specified))

widget = QColorBarWidget(self, BAR_TYPE_VALUE)
widget.setColor(QColor(0,0,0,0)) #Set color
color = widget.getColor() #Get color
colorBar.colorChanged.connect(onUpdateColor) # signal-slot

If you want to display multiple color pickers like Photoshop or Painter and link the colors, receive the color change with signal () of colorChanged and link with other widgets.


QColorBarWidget.py


from __future__ import division, print_function, unicode_literals, absolute_import

from PySide.QtGui import *
from PySide.QtCore import *

# TYPE
BAR_TYPE_HUE = 0
BAR_TYPE_SATURATION = 1
BAR_TYPE_VALUE = 2
BAR_TYPE_ALPHA = 3
BAR_TYPE_MAX = 4

Lupe_Color = [
    QColor(0, 0, 0, 255),
    QColor(0, 0, 0, 255),
    QColor(255, 255, 255, 255),
    QColor(255, 0, 0, 255)
]


class QColorBarWidget(QGraphicsView):
    colorChanged = Signal(str)

    def __init__(self, parent, type=BAR_TYPE_HUE):
        super(QColorBarWidget, self).__init__(parent)
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)
        self.width = 0

        self.type = type if type < BAR_TYPE_MAX else BAR_TYPE_HUE
        self.lupe_color = Lupe_Color[type]

        self.color = QColor()
        self.color.setHsv(0, 255, 255, 255)
        self.setColor(self.color)

        # BG
        pixmap = QPixmap(QSize(16, 16))
        tile = QPainter(pixmap)
        tile.save()
        brush1 = QBrush(QColor(128, 128, 128))
        brush2 = QBrush(QColor(168, 168, 168))
        tile.fillRect(0, 0, 8, 8, brush1)
        tile.fillRect(8, 8, 8, 8, brush1)
        tile.fillRect(8, 0, 8, 8, brush2)
        tile.fillRect(0, 8, 8, 8, brush2)
        tile.restore()
        tile.end()
        self.bg_brush = QBrush(pixmap)

    def drawBackground(self, painter, rect):
        """
        :type rect: QRectF
        :type painter: QPainter
        """
        painter.save()
        painter.fillRect(rect, self.bg_brush)
        painter.restore()

    def drawForeground(self, painter, rect):
        """
        :type rect: QRectF
        :type painter: QPainter
        """
        painter.save()
        painter.translate(rect.center())
        painter.setRenderHint(QPainter.Antialiasing, True)
        self.width = rect.toRect().width()
        half_width = self.width / 2
        height = rect.toRect().height()
        half_height = height / 2
        # bar
        gradient = QLinearGradient(-half_width, 0, half_width, 0)
        self.makeGradient(gradient)
        painter.setBrush(gradient)
        painter.drawRect(-half_width, -half_height, self.width, height)
        # lupe
        painter.setPen(QPen(self.lupe_color, 1))
        painter.setBrush(QColor(0, 0, 0, 0))
        half_width = self.px - half_width
        painter.drawEllipse(half_width - 2, 2 - half_height, 5, 5)
        painter.fillRect(half_width, 6 - half_height, 1, height, QBrush(self.lupe_color))

        painter.restore()

    def mouseMoveEvent(self, event):
        self.clickToColor(event)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.clickToColor(event)

    def clickToColor(self, event):
        self.px = event.pos().x()
        param = self.px / self.width
        param = 0 if param < 0 else param
        if self.type == BAR_TYPE_HUE:
            self.color.setHsv(360 * param, self.color.saturation(), self.color.value(), self.color.alpha())
        elif self.type == BAR_TYPE_SATURATION:
            self.color.setHsv(self.color.hue(), 255 * param, self.color.value(), self.color.alpha())
        elif self.type == BAR_TYPE_VALUE:
            self.color.setHsv(self.color.hue(), self.color.saturation(), 255 * param, self.color.alpha())
        else:  # alpha
            self.color.setAlphaF(param)

        self.colorChanged.emit('colorChanged')
        self.scene.update()

    def getColor(self):
        return (self.color)

    def setColor(self, color):
        self.color = QColor(color)
        if self.type == BAR_TYPE_HUE:
            self.px = color.hue() * self.width / 360
        elif self.type == BAR_TYPE_SATURATION:
            self.px = color.saturation() * self.width / 255
        elif self.type == BAR_TYPE_VALUE:
            self.px = color.value() * self.width / 255
        else:  # alpha
            self.px = color.alpha() * self.width / 255
        self.scene.update()

    def makeGradient(self, gradient):
        color = QColor()
        if self.type == BAR_TYPE_HUE:
            for _ in range(11):
                color.setHsv(_ * 36, 255, 255, 255)
                gradient.setColorAt(0.1 * _, color)
        elif self.type == BAR_TYPE_SATURATION:
            color.setHsv(360, 0, 255, 255)
            gradient.setColorAt(0.0, color)
            color.setHsv(360, 255, 255, 255)
            gradient.setColorAt(1.0, color)
        elif self.type == BAR_TYPE_VALUE:
            color.setHsv(360, 255, 0, 255)
            gradient.setColorAt(0.0, color)
            color.setHsv(360, 255, 255, 255)
            gradient.setColorAt(1.0, color)
        else:  # alpha
            color.setRgb(255, 255, 255, 0)
            gradient.setColorAt(0.0, color)
            color.setRgb(255, 255, 255, 255)
            gradient.setColorAt(1.0, color)
        return

sample.py


from __future__ import division, print_function, unicode_literals, absolute_import

from PySide.QtGui import *
from PySide.QtCore import *
import sys

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(300, 100)

        self.colorBar1 = QColorBarWidget(self)
        self.colorBar1.resize(150, 20)

        self.colorBar2 = QColorBarWidget(self, BAR_TYPE_HUE)
        self.colorBar2.resize(250, 30)
        self.colorBar2.move(0, 30)

        self.colorBar3 = QColorBarWidget(self, BAR_TYPE_ALPHA)
        self.colorBar3.resize(200, 20)
        self.colorBar3.move(50, 70)

        self.colorBar1.colorChanged.connect(self.onUpdateColor1)
        self.colorBar2.colorChanged.connect(self.onUpdateColor2)

    @Slot()
    def onUpdateColor1(self):
        color = self.colorBar1.getColor()
        self.colorBar2.setColor(color)

    @Slot()
    def onUpdateColor2(self):
        color = self.colorBar2.getColor()
        self.colorBar1.setColor(color)

def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

Recommended Posts

Create a color bar with Python + Qt (PySide)
Create a color-specified widget with Python + Qt (PySide)
Create a color picker for the color wheel with Python + Qt (PySide)
Create a directory with python
Create a virtual environment with Python!
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a word frequency counter with Python 3.4
Create a frame with transparent background with tkinter [Python]
Create a Python module
Create a LINE BOT with Minette for Python
Create a virtual environment with conda in Python
Create a page that loads infinitely with python
[Note] Create a one-line timezone class with python
You can easily create a GUI with Python
Create a python3 build environment with Sublime Text3
Steps to create a Twitter bot with python
Create a decision tree from 0 with Python (1. Overview)
Create a new page in confluence with Python
Create a Photoshop format file (.psd) with python
Create a Python environment
Create a Python console application easily with Click
Why not create a stylish table easily with Python?
Create a python development environment with vagrant + ansible + fabric
Fill the background with a single color with OpenCV2 + Python
Create a Layer for AWS Lambda Python with Docker
[python] Create a date array with arbitrary increments with np.arange
[Python] How to create a 2D histogram with Matplotlib
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a fake Minecraft server in Python with Quarry
Create a company name extractor with python using JCLdic
Create a 2d CAD file ".dxf" with python [ezdxf]
Create a Wox plugin (Python)
Create a function in Python
Create a dictionary in Python
Create 3d gif with python3
Create a homepage with django
[Python] Adjusting the color bar
Create a python numpy array
Make a fortune with Python
Create a heatmap with pyqtgraph
[Python] Create a file & folder path specification screen with tkinter
Create a list in Python with all followers on twitter
Create a child account for connect with Stripe in Python
Let's create a script that registers with Ideone.com in Python.
Probably the easiest way to create a pdf with Python3
Let's create a PRML diagram with Python, Numpy and matplotlib.
Detect objects of a specific color and size with Python
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Create a simple video analysis tool with python wxpython + openCV
Create a simple Python development environment with VSCode & Docker Desktop
Create a python machine learning model relearning mechanism with mlflow
Create a pixel art of Levi Captain with Python programming!
Create a message corresponding to localization with python translation string
[Python] Create a screen for HTTP status code 403/404/500 with Django
[Python] What is a with statement?
Solve ABC163 A ~ C with Python
Create plot animation with Python + Matplotlib