QScrollArea, for some reason, is ignoring the contentMargins
setting when I set QGraphicsView as its widget. Looking at the snippet below, can someone please tell if I'm doing something wrong or it could be a bug in the SDK?
Snippet 1 (works perfect):
QWidget *appWindow = new QWidget;
QScrollArea *sa = new QScrollArea(appWindow);
sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
sa->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
sa->setContentMargins(50, 50, 50, 50);
QWidget *widgetToScroll = new QWidget(sa);
widgetToScroll->resize(5000, 5000);
sa->setWidget(widgetToScroll);
QVBoxLayout *appWindowLayout = new QVBoxLayout(appWindow);
appWindowLayout->addWidget(sa);
appWindow->setLayout(appWindowLayout);
appWindow->show();
Snippet 2 (It's like setContentMargins() call is ignored completely):
QWidget *appWindow = new QWidget;
QScrollArea *sa = new QScrollArea(appWindow);
sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
sa->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
sa->setContentMargins(50, 50, 50, 50);
QGraphicsView *widgetToScroll = new QGraphicsView(new QGraphicsScene(sa), sa);
widgetToScroll->setAlignment(Qt::AlignLeft | Qt::AlignTop);
widgetToScroll->resize(5000, 5000);
sa->setWidget(widgetToScroll);
QVBoxLayout *appWindowLayout = new QVBoxLayout(appWindow);
appWindowLayout->addWidget(sa);
appWindow->setLayout(appWindowLayout);
appWindow->show();
Thanks.
It looks like you are confusing the structure of how to nest a QGraphicsView and a QGraphicsScene. (Maybe it was just a typo?)
should be changed to
or
When you add a QWidget to a layout, you change the widget's parent. When you set a widget (or QGraphicsView) to a QScrollArea, you change that widget's parent. See Object Trees & Ownership for more information. So if you wanted to set up your QGraphicsView inside a QScrollArea your code would look like this:
As a side note...
When using QGraphicsViews with a QGraphicsScene, instead of setting the margins using a QScrollArea's setContentsMargins, I use the QGraphicsView automatic scrolling and just set the scene rect to have a larger margin that the size of my content like so:
The QGraphicsView includes quite a bit more than just automatic scrolling when needed. You can resize everything inside of it and quite a bit more. It is great for 2D layouts, interactions and animations. See Qt's Graphics View Framework at http://doc.qt.io/qt-5/graphicsview.html for more information.
Here is more information that may be useful when using margins and paddings: The Box Model used by QStyleSheets.
To make the content margins work properly for a QScrollArea widget I subclass it and manually set the viewport margins (which is a protected method in QT 4.7)