Search code examples
c++qtqpainter

How to break up a screen/window's QPainter to paint only a portion?


I am coding a game - I have a Board class that is composed of a table/grid of "Spaces" - both Spaces and the Board have a virtual method 'render' being passed a QPainter reference. I want to (if possible) use the painter for the main board and to pass to each Space JUST the rectangle of the space on the screen that it should paint. Is that possible?

Like if the board occupies a rectangle 0,0 -> 2000,2000 and the rectangle passed to the top left space would be 0,0->100,100 - the rectangle for the next space over would be 100,0->200,100 - but as far as it would see, its rectangle would just be 0,0->100,100 no matter what - so I could break up the work being done. Here's a simple example:

class Space
{
     // ...
public:
     //...
     virtual void render(QPainter *painter);
};

class Board
{
     QList<QList<Space>> mLstBoard;
public:
     // ...
     virtual void render(QPainter *painter);
};

class GamePanel : public QWidget
{
     Q_OBJECT
     Board *mBoard;
public:
     // ...
};

class MainWindow : public QMainWindow
{
     Q_OBJECT

     GamePanel mPnlMain;
public:
     //...
};

int main(int argc, char **argv)
{
     QApplication a(argc, argv);
     MainWindow wnd;
     wnd.show();
     return(a.exec());
}

Solution

  • You can call QPainter::translate() on the QPainter object you pass to the Space objects, in order to adjust the location of the origin-point that they "see" when they draw with it.

    If you want to mask what they draw to make sure they only draw within their allotted region, you can do that by calling QPainter::setClipRect() on the QPainter before calling their render() method.

    Of course, once you have done that, you might want to just go the whole way and make each Space into its own separate QWidget, and lay them out as child widgets using a QGridLayout, since that seems to be the direction you're headed anyway.