QSizePolicy Fixed example in pyside2

when you set the size policy property of widget to QSizePolicy::Fixed,  the size of widget is fixed. even if the space of layout is changed, the size of widget is fixed.

layout management of Qt manages the position and the size of nested widgets. but if any of widgets has fixed size policy, the widget is not handled by layout management.

widget has setFixedSize() function. if you use this function, the maximum size and minimum size of widget is set to that value.

let's check this behavior from example code.


from PySide2 import QtWidgets

app = QtWidgets.QApplication([])

window = QtWidgets.QWidget()
layout = QtWidgets.QHBoxLayout()
fixedSizedButton = QtWidgets.QPushButton("Fixed Widget")

print(fixedSizedButton.sizePolicy())
fixedSizedButton.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)


layout.addWidget(fixedSizedButton)
window.setLayout(layout)
window.show()

app.exec_()


I created window widget using QWidget(). and layout using QHBoxLayout(). and I also created fixedSizedButton using QPushButton like below.


window = QtWidgets.QWidget()
layout = QtWidgets.QHBoxLayout()
fixedSizedButton = QtWidgets.QPushButton("Fixed Widget")

the reason why I created layout is that we need extra spaces for widget. the space of window widget is fixed to the needed size of children. so, there is no space if we just use window widget.

built-in widgets have its own size policy. in the case of QPushButton, horizontal size policy is Minimum and vertical size policy Fixed. so, I changed the size policies to fixed for both of them like below.


fixedSizedButton.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)

then, I added the fixed size button to layout and set the layout to window widget.


layout.addWidget(fixedSizedButton)
window.setLayout(layout)

finally, I execute Qt application. the result is like below.







the first one is default window size. and I tried to resize the window like second image.
although I changed the size of window, the size of button is fixed.







Comments

Popular posts from this blog

making menubar and menu on QML

let's start QML programming with PySide2