Layout is wrong at program start, adjusts once window is resized by hand.
-
Hello,
I have another problem I'm really stuck on: I created a board game which is resizeable and adjusts the positions of all pieces on the board according to the new size. This happens in resizeEvent of a custom Widget derived from QWidget.
Even if I execute the code inside the constructor, or call resize(size()) at the end of the constructor, nothing happens. However, if I perform this little hack with a timer, after a short period the layout will correctly adjust (just like it will when I resize by hand):
Board::Board(...) { ... connect(timer, &QTimer::timeout, this, [this] { resize(size() + QSize(1, 1)); }); timer->start(2000); }
Has anyone ever encountered this sort of issue? The Board has a layout which contains a single QLabel (as a background image). By setting the contextMargins, I keep the label centered in the window and its aspect ratio is preserved. Additionally, I have about 30 more QLabel objects, also children of the Board, but not part of the layout. These are moved to fit onto the board accordingly.
I really hope I can resolve this, and make my board look correct instantly, and not using this sort of hack.
P.S.: Another thing which really confuses me: I allocate the board already in my MainWindow. Then I add it as a stackedWidget page and simply set its index as current index when the start button is clicked. However, the timer I set in the Board constructor still only starts running once I change the stackedWidget page to the board widget. Is this to be expected?
-
Hi,
Until your widget is shown it has no size hence calling resize in the constructor will not have the effect you expect.
I think I more or less understand what it is about but can you provide a minimal compilable example that shows that behaviour ?
-
Until your widget is shown it has no size hence calling resize in the constructor will not have the effect you expect.
You gave me the information I needed, after quick google I came up with the following solution:
void Board::showEvent(QShowEvent *event) { QCoreApplication::postEvent(this, new QResizeEvent(size(), size())); }
This works as I intend. Thanks again!