我想在我的 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()));
}