Zheden
Zheden

Reputation: 593

Display image on whole QGraphicsScene in Qt

I want the graphics scene to show image that covers it whole. I create the scene with same size as an image, but get this result:

enter image description here

Could you please suggest what is wrong with the code? Thanks

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QGraphicsPixmapItem * image = new QGraphicsPixmapItem(QPixmap("C:\\data\\99.png"));
    int imageWidth = image->pixmap().width();
    int imageHeight = image->pixmap().height();
    image->setOffset(- imageWidth / 2, -imageHeight / 2);
    image->setPos(0, 0);

    QGraphicsScene *scene = new QGraphicsScene();
    scene->setSceneRect(-imageWidth / 2, -imageHeight / 2, imageWidth, imageHeight);
    QGraphicsView * gv = new QGraphicsView();
    ui->gridLayout->addWidget(gv);
    gv->setScene(scene);

    qInfo()<<"width image " <<imageWidth; // 640
    qInfo()<<"height image " <<imageHeight; // 400
    qInfo()<<"width scene " <<scene->width(); // 640
    qInfo()<<"height scene " <<scene->width(); // 400
    gv->scene()->addItem(image);
    gv->show();

}

Upvotes: 2

Views: 2620

Answers (1)

Tomaz Canabrava
Tomaz Canabrava

Reputation: 2418

The scene has the same size of the image, but the View doesn't, the view can be freely scalled.

what you need is to make the View to understand that the scene should be 100% of the view.

for this, create a class that inherit from QGraphivsView and override the resizeEvent, implement the following:

void GraphicsView::resizeEvent(QResizeEvent *event)
{
    QGraphicsView::resizeEvent(event);
    fitInView(sceneRect(), Qt::IgnoreAspectRatio);
    fixBackgroundPos();
}

this will always zoom the QGraphivsView to fit the whole scene.

Upvotes: 2

Related Questions