Search code examples
qtscrollqgraphicsview

QGraphicsView: Disable automatic scrolling


I want to have a QGraphicsView that never scrolls automatically.

Similar: Basically, my question is identical to http://developer.qt.nokia.com/forums/viewthread/2220 , but that thread didn't receive an answer.

What I have tried so far:

  • Within showEvent() and resizeEvent(), I do ui->graphicsView->fitInView(...), which works fine as long as items do not overshoot the screen-rectangle
  • I've also tried manipulating the view transform, but apart from scaling it's coefficients never change, so this was fruitless, too
  • Diabling scroll bar appearance does not help, too

See also http://doc.qt.io/qt-4.8/qgraphicsview.html.


Solution

  • I found a solution (don't hesitate to post your alternatives :) ), still I thought this answer might be helpful as I struggled on google and documentations for like 15 hours.

    The key is to not only call fitInView(), but also setSceneRect(). This did it for me (replace FooBar with your own class name):

    void FooBar::resizeEvent(QResizeEvent *) {
            fitView();
    }
    
    void FooBar::showEvent(QShowEvent *) {
            fitView();
    }
    
    void FooBar::fitView() {
            const QRectF rect = QRectF(-0.5,-0.5, 1, 1);
            ui->graphicsView->fitInView(rect,
                                        Qt::KeepAspectRatio);
            ui->graphicsView->setSceneRect(rect);
    }