【问题标题】:How to get visible scene rectangle of QGraphicsView?如何获得 QGraphicsView 的可见场景矩形?
【发布时间】:2011-12-28 02:06:09
【问题描述】:

我正在显示一个构建为 QGraphicsPixmapitem 项目矩形的地图(每个项目代表一个地图图块)。因为我的地图非常大(大约 30 MB 的 PNG 文件),我希望能够仅在 QGraphicsView 中对用户可见时按需加载像素图,并在它们变得不可见时卸载。

有没有办法找出可见的场景矩形?

【问题讨论】:

标签: qt qgraphicsview


【解决方案1】:

这为您提供了可见的场景矩形:

sceneRect = graphicsView.mapToScene(graphicsView.rect()).boundingRect()

如果存在剪切或旋转变换,它会为您提供可见场景区域的边界矩形。如果您没有此类转换(仅移动或缩放),则返回的矩形就是确切的场景区域。

现在解决在场景中高效显示巨大瓷砖地图的真正问题了吗?您可以在背景中加载图块并首先评估您的 Qt 框架是否尚未针对可见范围之外的大像素图进行优化。 30 MB 听起来也不大,以至于无法放入内存。

【讨论】:

    【解决方案2】:

    QGraphicsView 继承了 QWidget::geometry() 函数。您可以使用它来确定其在其父窗口小部件中的位置和大小。 (在其构造函数之外)

    QGraphicsScene 可以大于 QGraphicsView。默认的 QGraphicsView 将添加水平和垂直滚动条来容纳 QGraphicsScene。我想你想做这样的事情:

    //create a QGraphicsScene (for this example *scene) that is the size of your entire map.
    QGraphicsScene *scene=new QGraphicsScene(0,0,mapWidth,mapHeight);
    //create a QGraphicsView* named view that is the size of your visible area
    //I'm assuming visibleHeight and visibleWidth do not change (this is your viewing window)
    QGraphicsView *view=new QGraphicsView(0,0,visibleWidth,visibleHeight);
    view->setScene(scene);
    

    让用户控制触发某些自定义信号(如sceneMoved(int,int))的场景的 x 和 y 位置。在重绘场景之前,调用一个槽来检查场景的新位置:

    connect(this,SIGNAL(sceneMoved(int,int)),this,SLOT(drawScene(int,int)));
    
    void SomeClass::drawScene(int newX, int newY){
    //if you already have a pointer to the scene do this, or call
    //QGraphicsView::scene();
        int oldX=scene->geometry()->x();
        int oldY=scene->geometry()->y();
        //now that you have your oldX, oldY, newX, and newY, visibleWidth, visibleHeight
        //you can determine what you need to redraw, what you need to delete, and what can stay
    }
    

    还有很多 if..else,但你明白了。我建议尝试将您的地图分割成可见区域大小的正方形。

    【讨论】:

    • 什么是sceneMoved信号? id 在 Qt4 中不存在
    • 这是一个自定义信号,由用户触发。它确实需要澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2011-10-17
    相关资源
    最近更新 更多