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 QLabels have setWordWrap(True) and contain text which may be longer than the fixed width of the QScrollArea. When the text inside a QLabel wraps to ~4 lines, everything works fine, but when the QLabel requires more than that, it fails to continue increasing the height of the QLabel, and cuts off some of the text on the top and bottom.
This answer tried to fix essentially the same issue, which involves setting the QLabel's vertical sizePolicy() to MinimumExpanding, and this technically worked, but it will force the QLabels to try and fill the entire QScrollArea viewport if the viewport hasn't been filled with QLabels yet.
Here's how it currently looks without the sizePolicy set to MinimumExpanding (notice the 1st QLabel):
Here's how it looks when MinimumExpanding is set as the vertical size policy of the QLabels (Looks great...):
But it results in this behavior when there is only a few QLabels in the scroll area, which is unacceptable behavior, as this is going to be a "comments" service, where people can post their questions in plain text:
Does anyone have a workaround for this issue, or experience anything similar to it?
For reference, here is some of my code:
class NewsList(QtWidgets.QScrollArea):
def __init__(self, parent=None):
super(NewsList, self).__init__(parent)
self.setMaximumWidth(200)
self.setWidgetResizable(True)
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(5, 5, 5, 5)
layout.setSpacing(5)
layout.setAlignment(QtCore.Qt.AlignTop)
self.news_widget = QtWidgets.QFrame()
self.news_widget.setStyleSheet("""
QFrame {
background-color: #ffffff;
}
""")
self.news_widget.setLayout(layout)
self.setWidget(self.news_widget)
self.fetch_news()
def fetch_news(self):
self.append_message('DSADAISH dshadbsasdsadh sd ashd sah dsha dhsa dsa d')
self.append_message('DSADAISH dshadbsasdsadh sd ashd sah dsha dhsa dsa d')
self.append_message('DSADAISH dshadbsasdsadh sd ashd sah dsha dhsa dsa d DSADAISH dshadbsasdsadh sd ashd sah dsha dhsa dsa d')
self.append_message('DSADAISH ')
self.append_message('DSADAISH ')
self.append_message('DSADAISH dshadbsasdsadh sd ashd sah dsha dhsa dsa d')
self.append_message('DSADAISH dshadbsasdsadh sd ashd sah dsha dhsa dsa d')
def append_message(self, text):
new_item = QtWidgets.QLabel(text)
new_item.setWordWrap(True)
new_item.setStyleSheet("""
QLabel {
padding: 4px;
border: 1px solid black;
background-color: #ffffff;
}
""")


