How to get actual size of item in QGridLayout?
-
As the name of the topic suggests, how can I get the actual size of the widgets I add to QGridLayout. Looking at my code, when I print the dimensions, they are always equal to (640, 480).
I understand that sizeHint() is just a hint for the size of the widget, then, the size hint doesn't consider the size policy. In fact, the size policy tells how the size hint will be used to the layout manager. So how do I get the actual size of the item, can someone help me?
import sys from PySide6.QtWidgets import QApplication, QWidget, QStackedWidget, QVBoxLayout, QTextEdit, QGridLayout, QMainWindow class NewGrid(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.load_ui() def load_ui(self): self.showMaximized() self.central_widget = QWidget() self.central_layout = QVBoxLayout() grid_layout = QGridLayout() grid_layout.setSpacing(1) for row in range(0, 4): for col in range(0, 4): item = QWidget() item.setStyleSheet('background-color: lightblue;') grid_layout.addWidget(item, row, col) for row in range(0, 4): for col in range(0, 4): item = grid_layout.itemAtPosition(row, col) if item is not None: stacked_widget = item.widget() if isinstance(stacked_widget, QWidget): item_size = stacked_widget.size() print(f"Size of item at position ({row}, {col}): {item_size.width()} x {item_size.height()}") self.central_layout.addLayout(grid_layout) self.central_widget.setLayout(self.central_layout) self.setCentralWidget(self.central_widget) if __name__ == "__main__": app = QApplication(sys.argv) window = NewGrid() window.show() sys.exit(app.exec())
This is my ui:
-
@Hai-Anh-Luu Welcome to the forum.
Until the widget is displayed its size, and the size of any child widget in a layout, is unknown. In the widget class constructor^^ the widget is not yet shown so you get either the size hint from the widget concerned or some other value.
^^ That is when executing this line
window = NewGrid()
One way to see the size that is initially allocated is to do so in a slot connected to a zero-length (or very short) single-shot QTimer. This will fire when the event loop is reached, after the UI is shown. That is when
app.exec()
is running. -