How simply display a QColor using PyQt?


Question

I have a QColor that I get from a QColorDialog.getColor(). I would like to display it to the user within a form.

How can I do that ?

I tried using a QGraphicView and setting the backgroundBrush like this :

    self.displayColor = QtGui.QGraphicView(self)
    self.color = QtGui.QColor(category.color)
    self.displayColor.setBackgroundBrush(QtGui.QBrush(self.color))

But the widget stay white even if I change the backgroundbrush.

How can I force it to repaint the background ?

Thanks

1
2
1/7/2011 11:24:05 AM

Accepted Answer

Finally, I choose to create a widget like this :

# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore

class ColorDisplay(QtGui.QWidget):
    def __init__(self, parent):
        super(ColorDisplay, self).__init__(parent)

        self.color = None

    def setColor(self, color):
        self.color = QtGui.QColor(color)
        self.update()

    def paintEvent(self, event=None):
        painter = QtGui.QPainter(self)
        if self.color is not None:
            painter.setBrush(QtGui.QBrush(self.color))
            painter.drawRect(self.rect())

    def getColorName(self):
        return unicode(self.color.name())

I can change the color using setColor()

4
1/7/2011 3:42:22 PM

s=QGraphicsScene()
s.setBackgroundBrush(QColor(0,255,0))
g=QGraphicsView(s)
g.render(QPainter())

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon