C++ QGraphicscene::fitInView()仅适用于调整大小
我有一个发生在静态地图上的游戏。我想到了用QGraphicsView::trackground()绘制地图 一切似乎都很好。除非我调整窗口大小,否则不会绘制任何内容。。。我认为这与C++ QGraphicscene::fitInView()仅适用于调整大小,c++,qt,qt5,qgraphicsview,qgraphicsscene,C++,Qt,Qt5,Qgraphicsview,Qgraphicsscene,我有一个发生在静态地图上的游戏。我想到了用QGraphicsView::trackground()绘制地图 一切似乎都很好。除非我调整窗口大小,否则不会绘制任何内容。。。我认为这与qgraphicscene::fitInView()或相关的东西有关 Mymapscene.cpp #include "mapscene.h" #include <qpainter.h> #include <iostream> static const float WIDTH = 800.f;
qgraphicscene::fitInView()
或相关的东西有关
Mymapscene.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);
}
#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;
}
#包括“mapsecene.h”
#包括
#包括
静态常数浮动宽度=800.f;
静态常数浮动高度=480.f;
静态常量浮点映射[][2]={
{ 0, 0 },
{ 1, 1 },
//{1,0},//TEMP:地图的坐标
// { 0, 1 },
// { 0, 0 },
};
MapScene::MapScene():QGraphicscene(0,0,宽度,高度)
{
moveTo(_-map[0][0],_-map[0][0]);
int len=sizeof(_map)/sizeof(float)/2;
std::cout setScene(场景);
resizeEvent(0);
}
void主窗口::resizeEvent(QResizeEvent*)
{
QRectF bounds=ui->graphicsView->scene()->scene();
ui->graphicsView->fitInView(边界,Qt::keepasspectratio);
ui->graphicsView->centerOn(bounds.center());
std::cout scenpermit().width()scenpermit().height()由于大部分时间背景不会更改,因此默认情况下使用以下方法缓存背景:QGraphicsView::CacheBackground
。您有两个选项:
使用view.setCacheMode(QGraphicsView::CacheNone);
但它可能会降低性能
每次需要时在背景层上使用
即使第二个实现起来有点棘手,出于性能和CPU惰性的考虑,我还是推荐它。一个问题是std::cout问题是ui->graphicsView->fitInView(bounds,Qt::keepasspectratio);
在小部件实际显示之前不应调用:
应该没有必要在构造函数上强制重新绘制。但是,唉,我做了,而且仍然没有做任何事情…哦,谢谢。我不知道std::endl
和\n
之间有什么区别。现在消息被打印出来了,所以至少我知道问题不是因为paintBackground()
没有被调用。。。