⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

[SOLVED] QLabel and QScrollArea problem

  • Hello, I'm new in Qt and even in C++, I've got an issue, hope you can help me.
    I'm trying to put some pictures to the QScrollArea, as shown on the pictured below.
    I've tried some like this
    @void MainWindow::on_actionOpen_triggered()
    QFileDialog open(this);
    QStringList fileNames;
    if (open.exec()) fileNames = open.selectedFiles();
    QVBoxLayout labelLayout = new QVBoxLayout(ui->scrollArea);
    QDir dir(fileNames[0]);
    dir.setNameFilters(QStringList() <<"
    QStringList listOfImages = dir.entryList();
    QLabel *label;
    QPixmap *pic;
    int x = 20;
    int y = 20;
    for (int i=0; i < listOfImages.size();i++)
    pic = new QPixmap(fileNames[0]+ "/" + listOfImages[i]);
    label = new QLabel(this);
    // label->setFrameRect(QRect(
    // QPoint(x,y),
    // QSize(45,60)));

        y += -60;

    and I managed to get only this result =((
    Tell me please, what I've made wrong.
    Then I will try to implement pressing on any picture in QScrollArea and opening it in the QTabWidget ( on the right of QScrollArea). Maybe I shouldn't use QLabels for picture's preview? Maybe something like buttons with pictures will be better?

  • Moderators

    setGeometry() doesn't work inside a layout, because it's layout's responsibility to place it at the right posiition and shape it to fit (as it does in your case).
    The correct way to set fixed size of the label is to use setFixedSize().

    You also have a memory leak - the label doesn't take ownership of the pixmap you pass to it, so the memory is never released. You should rather create the pixmap on the stack:
    QPixmap pic(fileNames[0]+ "/" + listOfImages[i]);
    //or just
    label->setPixmap(QPixmap(fileNames[0]+ "/" + listOfImages[i]));

  • Thanks for you help.
    I used setFixedSize for my pictures. Then put them on the QVBoxLayout,
    and addSpacing(20) between QLabels. But QScrollArea resizes the QVBoxLayout according to the self size, and all pictures inside layout are resize respectively. QScollArea insted of creating a vertical scroll bar resizes content.
    I feel that I missed something, some setting for scroll area, but can't find what exactly.

  • Moderators

    Oh yeah, I haven't noticed it before. You shouldn't put a layout on the scroll area itself or just make a layout with scroll area as a parent.
    You should put the layout on some container widget and put that into the scroll area eg.
    ui->scrollArea()->setWidget(new QWidget());
    ui->scrollArea()->widget()->setLayout(new QVBoxLayout());


  • Thanks you very much!

Log in to reply