2010-03-22 148 views
5

我想在我的QGraphicsView中有一个背景图像,它总是按比例缩放(如果需要裁剪)到视口的大小,没有滚动条,也不用滚动键盘和鼠标。下面的示例是我在缩放和裁剪视口中的图像时所做的工作,但是我使用从以太网中拔出的裁剪的随机值。我想要一个合理的解决方案?QGraphicsView滚动和图像缩放/裁剪

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{ 

    ui->setupUi(this); 
    scene = new QGraphicsScene(this); 

    ui->graphicsView->resize(800, 427); 
    // MainWindow is 800x480, GraphicsView is 800x427. I want an image that 
    // is the size of the graphicsView. 

    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 
    // the graphicsView still scrolls if the image is too large, but 
    // displays no scrollbars. I would like it not to scroll (I want to 
    // add a scrolling widget into the QGraphicsScene later, on top of 
    // the background image.) 


    QPixmap *backgroundPixmap = new QPixmap(":/Valentino_Bar_Prague.jpg"); 
    QPixmap sized = backgroundPixmap->scaled(
      QSize(ui->graphicsView->width(), 
        ui->graphicsView->height()), 
      Qt::KeepAspectRatioByExpanding); // This scales the image too tall 

    QImage sizedImage = QImage(sized.toImage()); 
    QImage sizedCroppedImage = QImage(sizedImage.copy(0,0, 
     (ui->graphicsView->width() - 1.5), 
     (ui->graphicsView->height() + 19))); 
    // so I try to crop using copy(), and I have to use these values 
    // and I am unsure why. 

    QGraphicsPixmapItem *sizedBackground = scene->addPixmap(
     QPixmap::fromImage(sizedCroppedImage)); 
    sizedBackground->setZValue(1); 
    ui->graphicsView->setScene(this->scene); 
} 

我想知道的方式来扩展和裁剪图像到的QGraphicsView当我调整的QGraphicsView会甚至工作的大小。 1.5和19从哪里来?

编辑;我也尝试使用setBackgroundBrush,但是我得到了平铺背景,即使使用缩放/裁剪的QImage/QPixmap。

编辑;到目前为止,我的解决方案是重写drawBackground()以获得我想要的结果,但这仍然不能帮助我学习如何将图像调整为qgraphicsview的视口大小。任何进一步的答案将不胜感激。

void CustomGraphicsView::drawBackground(QPainter * painter, const QRectF & rect) 
{ 

    qDebug() << "background rect: " << rect << endl; 

    QPixmap *backgroundPixmap = new QPixmap(":/Valentino_Bar_Prague.jpg"); 
    QPixmap sized = backgroundPixmap->scaled(QSize(rect.width(), rect.height()), Qt::KeepAspectRatioByExpanding); 

    painter->drawPixmap(rect, sized, QRect(0.0, 0.0, sized.width(), sized.height())); 

} 

回答

1

你想sceneRect不仅仅是widthheight。对于调整缩放比例,您希望将插槽连接到sceneRectChanged,以便在场景更改大小时调整图像大小。

或者您可以派生一个QGraphicsView,并覆盖updateSceneRect来改变图像大小,或者更好的是,只需覆盖drawBackground

+0

从文档:“现场RECT定义场景的范围,并在视图的情况下,这意味着您可以导航使用场景区域滚动条“。 sceneRect不是我想要的,它给了我场景的大小,而不管视口尺寸是什么。我想要视口尺寸。我想调整图像的尺寸。这似乎很简单;抓住qgraphicsview的宽度/高度并完成工作。但是当我将图像缩放到这个尺寸时,宽度和高度是不正确的:这里缺少的部分是什么? 我会尝试drawBackground。 – user298725 2010-03-23 03:17:15

0

我找到ui->graphicsView->viewport()->size()来获得视口的大小。只有在绘制小部件后才能使用。

0

QGraphicsView::fitInView正是如此。根据文件,它通常放在resizeEvent。使用sceneRects使得整个场景配合到视图:

void CustomGraphicsView::resizeEvent(QResizeEvent *) 
{ 
    this->fitInView(this->sceneRect()); 
}