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

How to resize QWidget to fit its contents?



  • Hi,

    Basically I have a QTableWidget inside a QVBoxLayout. I set everything so that my table widget resizes to fit the contents. This is good, but I can't get my QWidget that hosts this table widget to resize itself to show everything.

    I checked tablewidget.size() but the size is not the correct size, because if I use the same size for my QWidget, the table is cropped, i.e. I can't see it fully.

    How can I achieve this?

    Thanks in advance.



  • try tableWidget->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);



  • @VRonin Thanks a lot, you are right it works :) I have another issue about the row heights, I am trying to resize them but they don't seem to get smaller in height than this:

    alt text

    I am doing it like this:
    ```
    hh = tableWidget.horizontalHeader()
    hh.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)

        hh.setFixedHeight(50)
        #hh.setStretchLastSection(True)
    
        vh = tableWidget.verticalHeader()
        vh.setSectionResizeMode(QtWidgets.QHeaderView.Fixed)
        vh.setDefaultSectionSize(1)
    
    
    I don't understand why row heights refuse to get smaller.

  • Lifetime Qt Champion

    @lachdanan
    Hi
    There is
    vh.setMinimumSectionSize(xx);
    and setDefaultSectionSize won't go under that value
    so you must lower that first to go really low.



  • @mrjj said in How to resize QWidget to fit its contents?:

    setMinimumSectionSize

    Thanks a lot I just tried that but no luck, and if I remove default section size function call, then they get larger:

    vh.setDefaultSectionSize(1)
    vh.setMinimumSectionSize(1)

    This still looks same size for example.



  • When I used this it worked: vh.setSectionResizeMode(QtWidgets.QHeaderView.Stretch)


Log in to reply