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

How to get actual widget width and height in constructor?



  • I want to adjust some items in a qtablewidget when ui satrted.
    And I put code in constructor of mainwindow class, then It didn't work.
    If I put same code in resizeEvent(), it worked.

        for (int r = 0; r < 5r++) {
            for (int c = 0; c < 5c++) {
                ui->TBW->setColumnWidth(c, ui->TBW->width/5);
            }
            ui->TBW->setRowHeight(r, ui->TBW->height/5);
        }
    

    How to get actual widget width and height in constructor?



  • @Qt_Andrew said in How to get actual widget width and height in constructor?:

    How to get actual widget width and height in constructor?

    You can't, because some events occur after constructing the widget, so the layouts and some other rules apply. This causes the widgets height and width to be different in constructor and after construction (at runtime after widget is shown).

    What you can do is setting a fixed size to make sure that your widget keeps the size, but then you cannot resize it anymore.

    EDIT:

    If your code works in resizeEvent, what prevents you from keeping it there?
    Instead of using the resizeEvent you could also use the showEvent from your parent widget (QMainWindow I guess), where your QTableWidget is located. Should have the same effect.



  • @Qt_Andrew said in How to get actual widget width and height in constructor?:

    How to get actual widget width and height in constructor?

    You can't, because some events occur after constructing the widget, so the layouts and some other rules apply. This causes the widgets height and width to be different in constructor and after construction (at runtime after widget is shown).

    What you can do is setting a fixed size to make sure that your widget keeps the size, but then you cannot resize it anymore.

    EDIT:

    If your code works in resizeEvent, what prevents you from keeping it there?
    Instead of using the resizeEvent you could also use the showEvent from your parent widget (QMainWindow I guess), where your QTableWidget is located. Should have the same effect.


Log in to reply