Qt GUI Development - Displaying a 2D grid using QGraphicsView

dlwells02 picture dlwells02 · Nov 26, 2011 · Viewed 22.6k times · Source

I'm new to Qt development so I've being trying to research a solution to a user interface I need to design. My project is to simulate players in an online game moving around a global map. To represent the map I need to display a 2D grid, with each space in the grid representing a region of a map. I then need to display the location of each player in the game. The back-end is all fully working, with the map implemented as a 2D array. I'm just stuck on how to display the grid.

The research I have done has led me to believe a QGraphicsView is the best way to do this, but I can't seem to find a tutorial relevant to what I need. If anyone has any tips on how to implement this it would be much appreciated.

Thanks, Dan

Answer

pnezis picture pnezis · Nov 26, 2011

A 2D Grid is nothing more than a set of horizontal and vertical lines. Suppose you have a 500x500 map and you want to draw a grid where the distance between the lines in both directions is 50. The sample code that follows shows you how you can achieve it.

// create a scene and add it your view
QGraphicsScene* scene = new QGraphicsScene;
ui->view->setScene(scene);

// Add the vertical lines first, paint them red
for (int x=0; x<=500; x+=50)
    scene->addLine(x,0,x,500, QPen(Qt::red));

// Now add the horizontal lines, paint them green
for (int y=0; y<=500; y+=50)
    scene->addLine(0,y,500,y, QPen(Qt::green));

// Fit the view in the scene's bounding rect
ui->view->fitInView(scene->itemsVBoundingRect());

You should check the QGraphicsView and the QGraphicsScene documentation as well as the corresponding examples. Also you can watch the graphics view training videos or some graphics view related videos from the Qt developer days.