2016-02-09 95 views
2

我有一个游戏发生在静态地图上。我想在QGraphicsView :: drawBackground()中绘制地图。QGraphicsScene :: fitInView()只适用于调整大小

一切似乎都在膨胀。除了没有什么,除非我做一个窗口大小调整绘制...我认为这与QGraphicsScene::fitInView()或相关的东西做...

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); 
} 

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; 
} 

我正在使用Qt 5.5.1(Ubuntu)。

编辑:我已经改变\nstd::endl为@LogicStuff建议,现在被印制的消息,所以drawBackground()获取调用。问题似乎与QGraphicsView::fitInView()QGraphicsView::centerOn()。我已经相应地改变了职位。

回答

0

由于大部分时间后台不会更改,因此默认情况下会缓存使用:QGraphicsView::CacheBackground。你有两个选择:

  1. 使用view.setCacheMode(QGraphicsView::CacheNone);可能你的背景层上每次需要时降低性能
  2. 使用invalidate(const QRectF & rect = QRectF(), SceneLayers layers = AllLayers)

即使第二个有点棘手实施,我会推荐它为了性能和CPU懒惰。

+0

它不应该是需要强制在构造一个重绘。但唉,我做了,仍然,什么也没做...... –

1

一个问题是std::cout << "draw background\n";MainWindow::drawBackground不刷新std::cout。另一方面,由于std::endlstd::coutMainWindow::resizeEvent中被刷新。使用std::endl\nstd::flush

+0

哦,谢谢。我不知道'std :: endl'和'\ n'之间是否有区别。现在消息被打印出来了,所以至少我知道问题不是因为'paintBackground()'没有被调用... –

相关问题