How To Resize Qlabels To Fit Contents In Qscrollarea
This issue is specific to PyQt5, but C++ Qt5 answers are fine too. Within a QScrollArea with fixed width and variable height, I have a QVBoxLayout that contains QLabels. These QLab
Solution 1:
This can be solved quite simply by using the addStretch
method of the layout that contains the news items:
classNewsList(QtWidgets.QScrollArea):def__init__(self, parent=None):
...
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(5, 5, 5, 5)
layout.setSpacing(5)
layout.setAlignment(QtCore.Qt.AlignTop)
# add a stretchable space to the bottom of the layout
layout.addStretch(1)
defappend_message(self, text):
...
# set the size policy of the label
new_item.setSizePolicy(
QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.MinimumExpanding)
# insert the label before the spacer
layout = self.news_widget.layout()
layout.insertWidget(layout.count() - 1, new_item)
The spacer pushes the labels upwards, which stops them streching to take up the available space. Using the stretch-factor argument of addStretch
ensures that the spacer always takes precedence over the other items in the layout.
Post a Comment for "How To Resize Qlabels To Fit Contents In Qscrollarea"