我想在我的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来自?

EDIT;我也尝试使用setBackgroundBrush,但我得到一个平铺的背景下,利用放大,即使/裁剪的QImage / QPixmap的。

EDIT;我的解决方案迄今已经覆盖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()));

}
有帮助吗?

解决方案

您想 sceneRect 不仅仅是widthheight。有关调整大小比例要插槽连接到 sceneRectChanged 这样你就可以调整图像的大小每当场景改变大小。

或者,可以推导出与改变重写 QGraphicsView 中的一个updateSceneRect图像大小,或更好的是,只是覆盖 drawBackground

其他提示

我发现ui->graphicsView->viewport()->size()获取视野的大小。只有作品后,该Widget的绘制虽然。

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

void CustomGraphicsView::resizeEvent(QResizeEvent *)
{
  this->fitInView(this->sceneRect());
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top