Get visible rectangle of QGraphicsView?

前端 未结 6 1451
借酒劲吻你
借酒劲吻你 2020-12-15 22:04

I\'ve been pulling my hair out with this one for hours. There\'s a thread here about it, but nothing seems to be working. QGraphicsView::rect() will return the width and hei

相关标签:
6条回答
  • 2020-12-15 22:29

    You can do what you've done, or use the mapToScene() functions. You can't count on the resulting scene "rectangle" being a rectangle, however, because the scene might be rotated or sheared in the view, resulting in a general polygon when mapped to the scene.

    If your application never does such things, of course, you're free to assume that a rectangle is always appropriate.

    0 讨论(0)
  • 2020-12-15 22:30

    It sounds like what you want is the scene rectangle. The ::rect() method is inherited from QWidget. See:

    http://doc.qt.io/qt-5/qgraphicsview.html#sceneRect-prop

    0 讨论(0)
  • 2020-12-15 22:34

    Nevermind. Came up with this, which seems to work.

    QRectF EditorView::visibleRect() {
        QPointF tl(horizontalScrollBar()->value(), verticalScrollBar()->value());
        QPointF br = tl + viewport()->rect().bottomRight();
        QMatrix mat = matrix().inverted();
        return mat.mapRect(QRectF(tl,br));
    }
    
    0 讨论(0)
  • 2020-12-15 22:34

    here is a possible solution (no clue whether this is the intended one)

    QRectF XXX::getCurrrentlyVisibleRegion() const
    {
            //to receive the currently visible area, map the widgets bounds to the scene
    
            QPointF topLeft = mapToScene (0, 0);
            QPointF bottomRight = mapToScene (this->width(), this->height());
    
            return QRectF (topLeft, bottomRight);
    }
    

    HTH, Bernhard

    0 讨论(0)
  • 2020-12-15 22:45

    Just map the pixel-based viewport rectangle to the scene using the view:

    graphicsView->mapToScene(graphicsView->viewport()->geometry()).boundingRect()
    

    Bye, Marcel

    0 讨论(0)
  • 2020-12-15 22:46

    The following implementation returned the best results for me:

    QRectF getVisibleRect( QGraphicsView * view )
    {
        QPointF A = view->mapToScene( QPoint(0, 0) ); 
        QPointF B = view->mapToScene( QPoint( 
            view->viewport()->width(), 
            view->viewport()->height() ));
        return QRectF( A, B );
    }
    

    This works still really well when scrollbars appear. This only works properly if the view does not display the scene rotated or sheared. If the view is rotated or sheared, then the visible rectangle is not axis parallel in the scene coordinate system. In this case

    view->mapToScene( view->viewport()->geometry() )
    

    returns a QPolygonF (NOT a QRectF) which is the visible rectangle in scene coordinates. By the way, QPolygonF has a member function boundingRect() which does not return the properly visible rectangle of the view, but might be useful anyways.

    0 讨论(0)
提交回复
热议问题