Qt5 C QGraphicsView:图像不适合视图框架

新手上路,请多包涵

我正在开发向用户显示他选择的一些图片的程序。但是有一个问题,因为我想把这张图片放在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 像素。有什么问题?

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

原文由 user1257255 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 733
2 个回答

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

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

 void YourClass::showEvent(QShowEvent *) {
    ui->graphicsView->fitInView(scn->sceneRect(),Qt::KeepAspectRatio);
}

原文由 user1257255 发布,翻译遵循 CC BY-SA 3.0 许可协议

你没有看到你想要的图像的原因是因为 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,如果您的视口位于正确的位置并且不希望它看起来像素化,请使用高分辨率图像。

原文由 TheDarkKnight 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题