Search code examples
qtqgraphicsview

QGraphicsView scroll bar policy not working as expected


I have a QGraphicsView with a vertical scroll bar policy of "ScrollBarAlwaysOff". The problem is that when I adjust the size of the view (via a QSplitter or just by adjusting the size of the window), a blank space will often appear on the right side of the view. Here's an example with a red background and a black QGraphicsRectItem:

#include <QtGui>

class MainWindow : public QMainWindow
{
public:
    MainWindow()
    {
        QGraphicsScene *scene = new QGraphicsScene(this);
        QRectF rect(-100, -100, 200, 200);
        QGraphicsRectItem *rectItem = new QGraphicsRectItem(rect);
        rectItem->setBrush(QBrush(Qt::black));
        scene->addItem(rectItem);
        scene->setSceneRect(rect); //commenting this out doesn't make a difference

        QGraphicsView *view = new QGraphicsView(this);
        view->setBackgroundBrush(QBrush(Qt::red));
        view->setTransformationAnchor(QGraphicsView::AnchorViewCenter);
        view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        view->setScene(scene);

        setCentralWidget(view);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

Here is what the problem looks like:

image of the problem

How can I fix this?

EDIT: Click here to make the picture a bit larger: https://i.sstatic.net/HeWHJ.png


Solution

  • I gave it a try and find that if you change your rectangle to (0, 0, 300, 300), it works as desired. It seems QGraphicsView has problem handling scroll bar update with negative top-left scene rect. You should file a bug report to Qt.