use*_*725 5 qt scale qpixmap qimage 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);
}
Run Code Online (Sandbox Code Playgroud)
我想知道一种方法来缩放和裁剪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()));
}
Run Code Online (Sandbox Code Playgroud)
你想要的sceneRect不仅仅是width和height。对于调整大小时的缩放,您需要连接一个插槽sceneRectChanged,以便在场景大小改变时可以调整图像大小。
或者您可以派生一个带有更改图像大小的QGraphicsView覆盖的,或者更好的是,只需覆盖。updateSceneRectdrawBackground
| 归档时间: |
|
| 查看次数: |
14359 次 |
| 最近记录: |