Search code examples
c++qtqt5qgraphicsviewqgraphicsscene

QGraphicsScene::fitInView() only works on resizing


I have a game that happens on top of a static map. I thought of painting the map in QGraphicsView::drawBackground().

All seems swell. Except that nothing is drawn unless I do a window resize... I think it has to do with QGraphicsScene::fitInView() or something related...

My mapscene.cpp

#include "mapscene.h"
#include <qpainter.h>
#include <iostream>

static const float WIDTH = 800.f;
static const float HEIGHT = 480.f;

static const float _map[][2] = {
    { 0, 0 },
    { 1, 1 },
//    { 1, 0 },  // TEMP: coordinates of map
//    { 0, 1 },
//    { 0, 0 },
};

MapScene::MapScene() : QGraphicsScene(0, 0, WIDTH, HEIGHT)
{
    mapPath.moveTo(_map[0][0], _map[0][0]);
    int len = sizeof(_map)/sizeof(float)/2;
    std::cout << len << std::endl;
    for(int i = 1; i < len; i++)
        mapPath.lineTo(QPointF(_map[i][0]*WIDTH, _map[i][1]*HEIGHT));
}

void MapScene::drawBackground(QPainter *painter, const QRectF &)
{
    std::cout << "draw background" << std::endl;
    painter->drawPath(mapPath);
}

My mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include "mapscene.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    MapScene *scene = new MapScene();
    ui->graphicsView->setScene(scene);
    resizeEvent(0);
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    QRectF bounds = ui->graphicsView->scene()->sceneRect();
    ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio);
    ui->graphicsView->centerOn(bounds.center());
    std::cout << "resize - scene rect: " << ui->graphicsView->sceneRect().width() << " x " << ui->graphicsView->sceneRect().height() << std::endl;
}

MainWindow::~MainWindow()
{
    delete ui;
}

I am using Qt 5.5.1 (Ubuntu).

EDIT: I have changed \n to std::endl as @LogicStuff suggested and now the message gets printed, so drawBackground() is getting called. The problem seems to be with QGraphicsView::fitInView() and QGraphicsView::centerOn(). I have changed the post accordingly.


Solution

  • The problem was that ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio); should not be called until the widget is actually shown:

    https://stackoverflow.com/a/17085612/2680707