16

我正在开发向用户显示他选择的一些图片的程序。但是有一个问题,因为我想把这张图片放在QGraphicsView的框架中,而图片确实比框架小。

所以这是我的代码:

image = new QImage(data.absoluteFilePath()); // variable data is defined when calling this method
scn = new QGraphicsScene(this); // object defined in header
ui->graphicsView->setScene(scn);
scn->addPixmap(QPixmap::fromImage(*image));
ui->graphicsView->fitInView(scn->itemsBoundingRect(),Qt::KeepAspectRatio);

我尝试了很多我在网上找到的解决方案,但没有人不帮助我。当框架为 200 x 400 像素时,图片的大小约为 40 x 60 像素。有什么问题?

下面是一些使用上面的代码生成的示例以及我想要得到的示例: 在此处输入图像描述

4

4 回答 4

23

我的问题的解决方案是 Dialog 的 showEvent()。这意味着您不能在显示表单之前调用 fitInView(),因此您必须为对话框创建 showEvent() 并且图片将适合 QGraphics View 的框架。

以及您必须添加到对话框代码中的示例代码:

void YourClass::showEvent(QShowEvent *) {
    ui->graphicsView->fitInView(scn->sceneRect(),Qt::KeepAspectRatio);
}
于 2013-06-13T11:10:58.833 回答
3

你没有看到你想要的图像的原因是因为 QGraphicsView 函数 fitInView 没有做你认为它做的事情。

它确保对象适合视口,视图边界没有任何重叠,因此如果您的对象不在视图中,调用 fitInView 将导致视图移动/缩放等以确保对象完全可见。此外,如果视口对于提供给 fitInView 的区域而言太小,则不会发生任何事情。

所以,为了得到你想要的,将 GraphicsView 坐标的范围映射到 GraphicsScene,然后将图像的场景坐标设置为那些。正如@VBB 所说,如果你拉伸图像,它可能会改变纵横比,所以你可以在 QPixmap 上使用 scaledToWidth 。

像这样的东西: -

QRectF sceneRect = ui->graphicsView->sceneRect(); // the view's scene coords
QPixmap image = QPixmap::fromImage(*image);

// scale the image to the view and maintain aspect ratio
image = image.scaledToWidth(sceneRect.width());

QGraphicsPixmapItem* pPixmap = scn->addPixmap(QPixmap::fromImage(*image));

// overloaded function takes the object and we've already handled the aspect ratio
ui->graphicsView->fitInView(pPixmap);

您可能会发现不需要调用 fitInView,如果您的视口位于正确的位置并且不希望它看起来像素化,请使用高分辨率图像。

于 2013-06-11T08:21:48.493 回答
0

你应该处理resize事件,我想这是它的播放方式:

bool YourDialog::eventFilter(QObject *obj, QEvent *event)
{
        if (event->type() == QEvent::Show){
            ui->conceptView->fitInView(conceptScene->sceneRect(), Qt::KeepAspectRatio);
        }

        if (event->type() == QEvent::Resize){
            ui->conceptView->fitInView(conceptScene->sceneRect(), Qt::KeepAspectRatio);
        }
}
于 2015-02-26T11:00:03.607 回答
0

我认为你应该缩放图像。我这样做并且效果很好:

QRect ref_Rect = QRect(x_pos, y_pos, Width, Length);
QGraphicsView* qGraph = new QGraphicsView(this);
qGraph->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
qGraph->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
qGraph->setGeometry(ref_Rect);

QGraphicsScene* scene = new QGraphicsScene(qGraph);
scene->setSceneRect(0, 0, ref_Rect.width(), ref_Rect.height());
qGraph->setScene(scene);

QImage *image = new QImage();
image->load("folder/name.png");
*image = image->scaled(ref_Rect.width(), ref_Rect.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); 
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(*image));    

scene->addItem(item);
qGraph->show();
于 2019-04-25T14:36:14.880 回答