Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Qt - C++ - ScrollArea - Resize content widgets by keeping the aspect ratio



  • I'm new to Qt and I've encountered the following problem.

    I have a layout that looks like this.

    Where:

    Blue: rectangle it's a ScrollArea

    Orange: rectangles are the widgets from that ScrollArea

    enter image description here


    The problem arises when I'm trying to resize the window. In the moment of resizing, I want my widgets to keep their aspect ratio. But that's not going to happen.

    Cases:

    • If I will scale my application vertically my widgets are going to get way higher then they should. Instead, they should keep their current size because any vertical scaling will destroy them
    • the same goes also for horizontal scaling
    • at the same time if I will scale on horizontal and vertical at the same time I should get the same number of elements from that scroll area on the view. Doesn't matter the size of them

    Now my question arises... this resizing problem is caused by the scroll area or by the widget itself? How can I fix this?


    My code:

    mainwindow.cpp

    ui->setupUi(this);
    
    ui->scrollArea->setWidgetResizable(true);
    
    for (auto i = 0; i < 10; ++i) {
        auto *targetWidget = new PolygonButtonWidget();//let it be target object
        ui->scrollAreaWidgetContents->layout()->addWidget(targetWidget);
    }
    QScroller::grabGesture(ui->scrollArea, QScroller::LeftMouseButtonGesture);
    

    Does anyone know how can I achieve my wanted result?


  • Lifetime Qt Champion

    Hi,

    Might be a silly question but if these red widgets have to be of an exact size, why not fix said size ?



  • @SGaist I'm not sure I understand the question... I don't want to make them be at fixed size because if I'm doing this I don't have any kind of scaling. Maybe I wasn't clear in my question but for example, if I will reduce the size of my windows with 50% I want that all that elements to look the same in terms of aspect ratio, not size. Or in other words... I want those red widgets to have a width of 5 and a height of 10 at 50% and 10 widths with 20 height at 100%.


  • Lifetime Qt Champion

    Then heightForWidth might be what you are looking for.



  • @SGaist ok... but where I should you that? Because if I'm using that function inside my widget, or inside of my code which I posted above I will get a -1 as a result because the widget itself doesn't have any layout at the beginning, he will be added into my scroll area layout.


  • Lifetime Qt Champion

    You have to reimplement that function for your custom class.


  • Lifetime Qt Champion

    Hi
    Just as a note
    I had to add this also
    https://doc.qt.io/qt-5/qwidget.html#hasHeightForWidth
    but maybe it returns default true now. was waaay back in Qt 5.0 :)


Log in to reply