在Qt中的整个QGraphicsScene上显示图像

时间:2017-05-29 10:10:54

标签: qt

我希望图形场景能够显示覆盖整个图像的图像。我创建了与图像大小相同的场景,但得到了这个结果:

enter image description here

您能否建议代码有什么问题?感谢

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

}

1 个答案:

答案 0 :(得分:2)

场景具有相同的图像大小,但视图没有,视图可以自由缩放。

您需要的是让View了解场景应该是视图的100%。

为此,创建一个继承自QGraphivsView的类并覆盖resizeEvent,实现以下内容:

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

这将始终缩放QGraphivsView以适应整个场景。