Search code examples
qtc++11qt5qwidget

How to use Qt QColormap in code?


I want to achieve something like this .
Color chart

I looked into the Qt QColormap but I did'nt get enough information to code it. If someone knows how to do this. Please share code snippet.


Solution

  • It's more question about color models then Qt really but basically you are trying to make a full circle around edge of HSL color model while keeping saturation.

    To produce something like that in Qt you will utilize gradient brush; since we want continuous blend I used QLinearGradient. If you look at the color wheel above you will notice that red color is at 0 degrees, green is at 120 degrees and blue is at 240 degrees. QLinearGradient works with range from 0-1 so this will transform to 0, 1/3, 2/3 respectively. We also need need to add final stop which will complete the gradient back to red color.

    I added bit of alpha channel to keep the color tone down so you can experiment with that; final code will look something like this:

    class ColorScale : public QWidget {
        Q_OBJECT
    public:
        using QWidget::QWidget;
    
    protected:
        void paintEvent(QPaintEvent *event) override {
            QPainter painter(this);
            painter.setOpacity(0.9);
            painter.setRenderHint(QPainter::HighQualityAntialiasing);
            QLinearGradient gradient(0, 0, 0, height());
            QGradientStops stops;
            stops << QGradientStop(0, Qt::red);
            stops << QGradientStop(1.0/3, Qt::blue);
            stops << QGradientStop(2.0/3, Qt::green);
            stops << QGradientStop(1, Qt::red);
    
            gradient.setStops(stops);
    
            painter.fillRect(rect(), gradient);
        }
    };
    

    And it produces this:

    Color scale

    You can add labels by calling QPainter::drawText.