Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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();
    }
    
    


  • @hobbyProgrammer

    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?

    https://doc.qt.io/qt-5/qgraphicsview.html#drawBackground



  • @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));
    }
    

  • Qt Champions 2019

    @hobbyProgrammer It looks like you do not check whether the image was actually loaded successfully.



  • @jsulm @Pl45m4 okay, but it keeps repeating the image and I would like there to be just 1 image, that can be zoomed in and out. Do you know how to do that?


Log in to reply