Search code examples
c++qtcolorsqpainterqtgui

Qt: making a stacked barchart with different colors


I'm trying to make a timeline in Qt, where a different color stands for a different task. Ultimately, it should look a bit like this (but only one line);

stacked

Now anyone got any ideas how to do this without installing extra libraries, but just with QPaint? The data it is representing is stored in a self-defined structure.

Any help is welcome.

Thx!


Solution

  • You seem to need something like the code below, although please note that it is just pseudo code, and the exact details depend a lot on how you get the data from your datastructure which you have not yet shared with us.

    ...
    QPainter *painter = new QPainter(MyPaintDevice); // MyPaintDevice could be even 'this'
    QPen pen(Qt::gray, 2);
    painter->setPen(pen);
    int currentX = 0;
    const int currentY = 0;
    const int height = hardCodedValue; // Coming from some static data initialization
    
    foreach (const Settings& settings, settingsList) {
        QBrush brush(QColor(settings.colorString()));
        painter->setBrush(brush);
        painter->drawRect(currentX, currentY, settings.width(), height);
        currentX += settings.width();
    }
    ...
    

    Admittedly, you would be better off going for QML rather than the old QPainter engine for several reasons. That is hardware accelerated these days rather than software rasterization as the QPainter approach, but probably more importantly for you: it is lotta simpler.

    You would need to look into the native Rect qml element, and probably the Repeater.