Automatically scaling PixMap to fill entire Graphics view (super grateful for any help)



  • Hi,

    I have a main window with a graphicsview. I am displaying a pixmap within it using a pixmapgraphics item. I would really like the pixmap to scale up or down automatically as I enlarge the window.
    I've got the graphicsView to grow and shrink as the user changes the size of the window but I don't know how to change the pixamp:

    My Class:

    class MainWindow : public QMainWindow
    {
    Q_OBJECT
    public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void resizeEvent(QResizeEvent *event) override;
    private:
    Ui::MainWindow *ui;
    QGraphicsView *graphicsView;
    QGraphicsScene *scene;
    QGraphicsPixmapItem *pixMapItem;
    QPixmap *myPixMap;
    QImage *image;

    public slots:

    };

    In the .cpp file:

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)

    {
    ui->setupUi( this );
    setWindowTitle("Experiment Scene");

    graphicsView = new MyGraphicsView;
    graphicsView->setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, "Test"));
    
    int w = 600;
    int h = 1400;
    
    scene = new QGraphicsScene(0,0,w,h);
    scene->setBackgroundBrush(Qt::black);
    

    // image = new QImage("/Users/virginiarutten/Qt/test.png");

    QPixmap pixmap("/Users/virginiarutten/Qt/test.png");
    
    pixMapItem = new QGraphicsPixmapItem(pixmap.scaled(w,h,Qt::KeepAspectRatio));
    pixMapItem->setFlag(QGraphicsItem::ItemIsMovable);
    pixMapItem->setPos(0,0);
    scene->addItem(pixMapItem);
    
    graphicsView->setScene(scene);
    graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
    graphicsView->resize(w, h);
    

    // graphicsView->show();
    or
    ui-> graphicsView->show();

    }

    I can only detect when the main window is being changed size using:

    void MainWindow::resizeEvent(QResizeEvent *) {
    qDebug() <<"";
    }

    I also tried just showing the graphics view (no window)
    i.e.: graphicsView->show();

    but in that case I don't know how to detect if the user has increased the size of the window.

    Please please do give any advice - I've been stuck on this problem for hours.

    Many thanks




Log in to reply