QGraphicsScene::fitInView()仅在调整大小时有效

3

我有一个在静态地图上进行的游戏。我想在QGraphicsView::drawBackground()中绘制地图。

一切都看起来很好。除了没有绘制任何东西,除非我调整窗口大小...我认为这与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)。
编辑:我已经按照@LogicStuff的建议将\n更改为std:: endl ,现在消息得到打印,因此drawBackground()被调用。问题似乎出在QGraphicsView :: fitInView()QGraphicsView :: centerOn()上。我已相应地更改了帖子。
3个回答

2

1
一个问题是,在MainWindow::drawBackground中的std::cout << "draw background\n";没有刷新std::cout。另一方面,由于std::endlMainWindow::resizeEvent中的std::cout被刷新了。

使用std::endl\nstd::flush


哦,谢谢。我不知道std::endl\n之间有什么区别。现在消息已经被打印出来了,所以至少我知道问题不是因为paintBackground()没有被调用... - Ricardo Magalhães Cruz

0

由于大多数情况下背景不会改变,因此默认情况下使用:QGraphicsView :: CacheBackground 进行缓存。您有两个选择:

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

即使第二种方法实现起来有点棘手,出于性能和 CPU 懒惰的考虑,我仍然建议使用它。


不应该在构造函数中强制重绘。但是,我尝试了却仍然没有任何效果... - Ricardo Magalhães Cruz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接