【问题标题】:How to keep image original in QgraphicsView in QT如何在 QT 中的 QgraphicsView 中保持图像原始
【发布时间】:2020-06-06 06:32:14
【问题描述】:

我已经在 QGraphicsView 中加载了一个图像,但是考虑到 QGraphicsView 场景的大小,我需要先缩放图像,然后将缩放后的图像添加到场景中。 例如图片原始大小为1536*1024,QGraphicsView大小为500*400,首先我是这样缩放图片的:

image2D = image2D.scaled( h * P , h, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
myScene->setSceneRect((h * P-w)/2, 0, h * P , h);
pixmapItem = new QGraphicsPixmapItem(image2D);
myScene->addItem(pixmapItem);
myView->setScene(myScene);

现在我遇到了一个问题,当 wheelEvent 发生并且 QGraphicsView 放大时,缩放后的图像变得模糊不清,而我希望它保持与原始图像一样清晰。 我找到了一种可以保存图像原始副本的方法,然后当 wheelEvent 发生时,只需缩放原始副本并将其放到场景中。 但是我不知道怎么写这段代码,谢谢帮助~ 或者有什么简单的方法吗?

class interactiveView : public QGraphicsView
{
protected:
    void wheelEvent(QWheelEvent *event) override;
}
void interactiveView::wheelEvent(QWheelEvent *event)
{
    int scrollAmount = event->delta();

    xPos = event->pos().x();
    yPos = event->pos().y();

    scrollAmount > 0 ? zoomIn() : zoomOut();
}

更新: 我找到了这样一个简单的方法: 只需使用QGraphicsView::fitInView() 确保图像比例等于QGraphicsView,不需要先缩放图像。 因此图像在放大时不会模糊,我只需要调用QGraphicsView::fitInView()重置为原始视图而不是使用QGraphicsView::resetMatrix()

void myImageWindow::loadImag(int w, int h)
{
     pixmapItem->setPixmap(image2D);
    //if the scale of image changed
    if(image2D.height() != imgHeight_pre){
        myView->fitInView(pixmapItem, Qt::KeepAspectRatioByExpanding);
        imgHeight_pre = image2D.height();
    }
    //if the scene of QGraphicsView changed
    if(h != sceneHeight_pre){
        myView->fitInView(pixmapItem, Qt::KeepAspectRatioByExpanding);
        sceneHeight_pre = h;
    }
}
void myImageWindow::on_rstImgBtn_clicked()
{
    myView->fitInView(pixmapItem, Qt::KeepAspectRatioByExpanding);
}

缩放图像:

放大后变得模糊:

【问题讨论】:

    标签: image qt scale mousewheel qgraphicsview


    【解决方案1】:

    你可以使用这个方法resetMatrix()重置图片

    例如

    graphicsView->scale(2, 2);
    graphicsView->resetMatrix();
    graphicsView->scale(1, 1);
    

    【讨论】:

    • 嗨,我找到了一个非常简单的方法:myView->fitInView(pixmapItem, Qt::KeepAspectRatioByExpanding);
    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多