Scaling pixmap images in qscrollarea

  • After many trials and tribulations and a lot of reading, I find myself in need of assistance from gurus who have dealt with images

    I am working on an application where I want to have an area that will display a variable number of images. The user will then select an image and drag it to a location on a simulated display page. The idea is to be able to position a variety of images at specific spots on multiple screen pages.

    I am looking to have two or more columns of images, appropriately scaled, in a scroll area. The entire application area is resizable, therefore, as space changes in the scroll area, the columns of images may grow or shrink as applicable.

    I have tried many, many different test runs working with QLabel and QPixmaps but have not found a way get them to work together nicely. Part of the issue is that I do not understand sizePolicy, QViewports, QSrollarea, sizeHint, etc., relationships.

    Any help in understanding how to have scalable images displayed in a scroll area will be greatly appreciated.

    Screen layout: Left size is scrollarea for images, right side is composing area.


    Current Test Code:

    void MainWindow::loadImages()

    #define NCOLS 2
    #define MAX_WIDTH 100

    QDir dir = QDir(imageLibrary);
    QStringList allImageFiles = dir.entryList(QStringList("*.jpg"));
    QRect geo_availImagesGeometry = ui->scrollArea->geometry();
    int width = geo_availImagesGeometry.width();   
    int height = geo_availImagesGeometry.height();
    QWidget * viewport = new QWidget;
    QGridLayout * gl = new QGridLayout(viewport);
    QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    for (int i = 0; i < allImageFiles.size(); i++) {
        QString thisfile = imageLibrary + "/" + allImageFiles[i];
        QPixmap pixmap(thisfile);
        QLabel * thisImage = new QLabel();
        //thisImage->setScaledContents(true); 	// Tried with and without this statement
        //pixmap.scaledToWidth(width);		// Tried with and without this statement
        thisImage->setPixmap(pixmap.scaled(width , width, Qt::KeepAspectRatio));
    //thisImage->setText(allImageFiles[i]);  // ????? Using this causes a segmentation violation
        gl->addWidget(thisImage, i/NCOLS, i % NCOLS);	// Add at row/column in scrollarea
    QRect scrollGeom = viewport->childrenRect();		// Check what
    ui->currentLibrary->setMaximumWidth(scrollGeom.width());	// Set width of library name to width of scroll area
    QList<QLabel *> vplist = viewport->findChildren<QLabel *>();	// Debug -- See what the viewport has to say about sizes


  • Lifetime Qt Champion


    What about using a QListView in icon mode with two columns ?

  • @sgaist

    Interesting idea. Will it scale pixmaps?

  • Lifetime Qt Champion

    Yes it will scale all images to match IconSize.