Unsolved Draw QPixmap in DrawBackground method from QGraphicsView
-
I would like to draw a QPixmap in the drawBackground method of a QGraphicsView class.
this is my GraphicsView.cpp
#include "graphicsview.h" GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent) { scene = new QGraphicsScene(this); setScene(scene); } void GraphicsView::scaleView(qreal scaleFactor) { qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width(); if (factor < 0.07 || factor > 100) return; scale(scaleFactor, scaleFactor); } void GraphicsView::drawBackground(QPainter *painter, const QRectF &rect) { Q_UNUSED(rect); QRectF sceneRect = this->sceneRect(); painter->drawPixmap(sceneRect, pixmap, pixmap.rect()); } void GraphicsView::zoomIn() { scaleView(qreal(1.2)); } void GraphicsView::zoomOut() { scaleView(1 / qreal(1.2)); } void GraphicsView::open() { QString filename = QFileDialog::getOpenFileName(this,tr("Open File"), QDir::currentPath(), tr("Image Files(*.png *.jpg *.jpeg)")); pixmap = QPixmap(filename); update(); }
-
You want to set an image (instead of just white) as background for your GraphicsView?
setBackgroundBrush(QImage("PATH"));
Where does your PixMap come from? External image file or painted inside your GraphicsScene as well?
-
@Pl45m4 okay, but then this should work, right?
I'm still getting a white background...#include "graphicsview.h" GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent) { scene = new QGraphicsScene(); this->setScene(scene); this->setAlignment(Qt::AlignLeft | Qt::AlignTop); LoadImage(); } void GraphicsView::LoadImage() { filename = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::currentPath(), tr("Image Files (*.png *.jpg *.jpeg)")); this->update(); } void GraphicsView::drawBackground(QPainter *painter, const QRectF &rect) { Q_UNUSED(rect) painter->setBackground(QImage(filename)); }
-
@hobbyProgrammer It looks like you do not check whether the image was actually loaded successfully.
-