Results 1 to 17 of 17

Thread: Drawing grids efficiently in QGraphicsScene

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    Join Date
    Jan 2006
    Location
    Norway
    Posts
    124
    Qt products
    Qt3 Qt4 Qt/Embedded
    Platforms
    MacOS X Unix/X11 Windows
    Thanked 38 Times in 30 Posts

    Default Re: Drawing grids efficiently in QGraphicsScene

    Using a cosmetic 0-width pen avoids unnecessary tesselation, calling QPainter::drawLines() is usually faster than QPainter::drawLine(), and using QGraphicsScene::drawBackground() is almost always faster than creating items. Here's an example that performs pretty well for me:

    Qt Code:
    1. class GridScene : public QGraphicsScene
    2. {
    3. public:
    4. GridScene(qreal x, qreal y, qreal w, qreal h)
    5. : QGraphicsScene(x, y, w, h)
    6. { }
    7.  
    8. protected:
    9. void drawBackground(QPainter *painter, const QRectF &rect)
    10. {
    11. const int gridSize = 25;
    12.  
    13. qreal left = int(rect.left()) - (int(rect.left()) % gridSize);
    14. qreal top = int(rect.top()) - (int(rect.top()) % gridSize);
    15.  
    16. QVarLengthArray<QLineF, 100> lines;
    17.  
    18. for (qreal x = left; x < rect.right(); x += gridSize)
    19. lines.append(QLineF(x, rect.top(), x, rect.bottom()));
    20. for (qreal y = top; y < rect.bottom(); y += gridSize)
    21. lines.append(QLineF(rect.left(), y, rect.right(), y));
    22.  
    23. qDebug() << lines.size();
    24.  
    25. painter->drawLines(lines.data(), lines.size());
    26. }
    27. };
    28.  
    29. int main(int argc, char **argv)
    30. {
    31. QApplication app(argc, argv);
    32.  
    33. GridScene scene(-1000, -1000, 2000, 2000);
    34. QGraphicsView view(&scene);
    35. view.rotate(33);
    36. view.show();
    37.  
    38. return app.exec();
    39. }
    To copy to clipboard, switch view to plain text mode 

    Notice the use of QVarLengthArray, that's a trick to avoid allocating memory. As long as no more than 100 grid lines are visible at the same time, it'll use the stack and nothing else. You can play with the size; a QLineF uses 32 bytes of memory so 100 of those means 3200 bytes of stack space; there's room for more.
    Bitto / Andreas Aardal Hanssen - andreas dot aardal dot hanssen at nokia
    Nokia Software Manager, Qt Development

  2. The following 2 users say thank you to Bitto for this useful post:

    Gopala Krishna (11th February 2007), sarbh20ss (30th November 2013)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.