Search code examples
c++qtgraphicsqgraphicsview

What is the best way to draw plots in Qt?


I am using Qt to draw a spectrogram like this:

spectrogram. I also want to be able to select regions of the graph and edit them, as well as scrolling and zooming around.

I am considering QGraphicsView class but not sure about its performance. As I know, the objects in QGraphicsView are stored individually and drawing a huge amount of dots might impact performance.

What Qt classes should I use to achieve this?


Solution

  • Definitely do not use the QGraphicsItem for every dot/mark. Good approach would be to generate a QPixmap representing your spectrogram and than place this pixmap into the QGraphicsScene as a single item (QGraphicsPixmapItem can be used for that).

    To draw on the QPixmap use the QPainter. Maybe a little example will be useful:

    const int spectrWidth = 1000;
    const int spectrHeight = 500;
    QPixmap spectrPixmap(spectrWidth, spectrHeight);
    QPainter p(&spectrPixmap);
    
    for (int ir = 0; ir < spectrHeight; ir++)
    {
        for (int ic = 0; ic < spectrWidth; ic++)
        {
            double data = getDataForCoordinates(ic, ir); // your function
            QColor color = getColorForData(data);  // your function
            p.setPen(color);
            p.drawPoint(ic, ir);
        }
    }
    

    The getDataForCoordinates() and getColorForData() are just example functions demonstrating how it could work. You have probably different way how to obtain data and it's color.

    EDIT

    But if you do not need a zoom/pan functionality than even easier would be just to paint directly on the QWidget in the QWidget::paintEvent() and not using the QGraphicsView/QGraphicScene at all.