Pregunta

Me gustaría tener una imagen de fondo en mi QGraphicsView que siempre se escala (y recorta si es necesario) para el tamaño de la ventana, sin barras de desplazamiento y sin necesidad de desplazarse con el teclado y el ratón. El siguiente ejemplo es lo que estoy haciendo a escala y recortar una imagen en la vista, pero yo estoy usando valores aleatorios para el cultivo que se sacó del éter. Me gustaría una solución lógica?

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);
}

Me gustaría saber una manera de escalar y recortar una imagen al tamaño de la QGraphicsView que funcionará incluso cuando cambio el tamaño de la QGraphicsView. ¿Dónde están los 1,5 y 19 procedentes de?

EDITAR; También he intentado usar setBackgroundBrush, pero me da un fondo de azulejos, incluso cuando se utiliza el escalado / recortada QImage / QPixmap.

EDITAR; Mi solución ha sido hasta ahora para anular drawBackground () para obtener el resultado que quería, pero esto todavía no me ayudará a aprender cómo el tamaño de una imagen al tamaño de la ventana gráfica de un QGraphicsView. Cualquier otra respuestas serían muy apreciados.

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()));

}
¿Fue útil?

Solución

sceneRect no sólo width y height. Para cambiar el tamaño de la escala en la que desea conectarse a una ranura sceneRectChanged para que pueda cambiar el tamaño de la imagen siempre que la escena cambia de tamaño.

O se puede derivar una QGraphicsView con un updateSceneRect que cambia el tamaño de la imagen, o mejor aún, simplemente anular drawBackground .

Otros consejos

He encontrado ui->graphicsView->viewport()->size() para obtener el tamaño de la ventana gráfica. Sólo funciona tras el widget ha dibujado sin embargo.

El QGraphicsView::fitInView hace exactamente esto. De acuerdo con la documentación, se pone comúnmente en una resizeEvent. Usando sceneRects hace que toda la escena encaja en la vista:

void CustomGraphicsView::resizeEvent(QResizeEvent *)
{
  this->fitInView(this->sceneRect());
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top