QGraphicsView margin offset in pixels
-
I've been unsuccessfully trying to create a graphics scene in which there are prescribed, constant margins (in pixels) from the border of the QGrpahicsView to the contents of the QGraphicsScene, such that these constant margins (in pixels) are kept on resize events.
Here's a simple test case:
#include <QApplication> #include <QApplication> #include <QGraphicsScene> #include <QGraphicsView> #include <QPainterPath> #include <QVBoxLayout> #include <QWidget> class View : public QGraphicsView { public: explicit View(QWidget *parent = nullptr) : QGraphicsView(parent) { setFrameStyle(QFrame::NoFrame); setScene(new QGraphicsScene); } protected slots: virtual void resizeEvent(QResizeEvent *event) override { // Set view such that a margin (in pixels) exist from each side int const pixelOffset = 30; QTransform matrix(1,0,0,0,1,0,0,0,1); matrix.scale((width()-pixelOffset)/sceneRect().width(), (height()-pixelOffset)/sceneRect().height()); setTransform(matrix); QGraphicsView::resizeEvent(event); } virtual void showEvent(QShowEvent *event) override { drawScene(); QGraphicsView::showEvent(event); } private: void drawScene() { scene()->clear(); // amount to offset in pixels QPointF const orig = QPointF(0,0); // Draw four lines (which happen to be in form of a closed box) QPainterPath path; path.moveTo(orig); path.lineTo(orig.x()+100, orig.y()); path.lineTo(orig.x()+100, orig.y()+100); path.lineTo(orig.x(), orig.y()+100); path.lineTo(orig); scene()->addPath(path); scene()->setSceneRect(QRectF(QPointF(0,0), QPointF(orig.x()+100,orig.y()+100)) ); } }; class Widget : public QWidget { public: explicit Widget(QWidget *parent = nullptr) : QWidget(parent) { auto layout = new QVBoxLayout(this); layout->addWidget(new View); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); Widget w; w.show(); return app.exec(); }
@
Please note that in the above example, only for simplicity I am using same margin on all sides to demonstrate the problem.
Problem I have is that although the (overall) margin is retained on resize, the margin oscillates slightly (1 or two pixels) on resize. I want to have the margin completely fixed on resize so that there is no visual movement of the four lines I have drawn on the screen.
Sorry if this post is not formatted correctly -- this webpage is completely broken on my browser (FireFox 41).