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

问题描述 投票:14回答:4

我正在制作程序,向用户显示由他选择的一些图片。但是有一个问题,因为我想在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像素。可能有什么不对?

以下是使用上面的代码生成的内容以及我想要获得的内容的一些示例:

c++ image qt qgraphicsview
4个回答
20
投票

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

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

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

1
投票

你没有看到你想要的图像的原因是因为QGraphicsView函数fitInView没有你想象的那样做。

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

因此,要获得所需内容,请将GraphicsView坐标的范围映射到GraphicsScene,然后将图像的场景坐标设置为这些坐标。正如@VBB所说,如果你拉伸图像,它可能会改变方面raio,所以你可以在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,如果您的视口位于正确的位置,并且您不希望它看起来像素化,请使用具有高分辨率的图像。


0
投票

你应该处理调整大小事件,我猜这是它的意思:

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

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();
© www.soinside.com 2019 - 2024. All rights reserved.