QLabel won't expand enough vertically
Unsolved
General and Desktop
-
In the following code, I've set up two QLabels inside a QHboxLayout. The first one is really long and has WordWrap set to true. The parent widget (which is the main widget of the window) has a fixed width. I'd expect the label to expand vertically following the size policies that have been set, and it does, even expanding more when using even longer text, but it's never enough to fit the whole text.
import sys from PyQt5.QtWidgets import ( QApplication, QLabel, QHBoxLayout, QFrame, QMainWindow, QSizePolicy ) from PyQt5.QtCore import Qt class TestWindow(QMainWindow): def __init__(self): super().__init__() # Main frame self.central_widget = QFrame() self.central_widget.setFixedWidth(640) self.setCentralWidget(self.central_widget) # Layout self.main_layout = QHBoxLayout(self.central_widget) self.main_layout.setContentsMargins(10, 10, 10, 10) self.main_layout.setSpacing(10) # Summary label self.summary_label = QLabel( self ) self.summary_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.summary_label.setText( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " "Ut at sem id tortor interdum facilisis. Donec orci tortor, ultrices sed dui nec, " "sollicitudin egestas ante. Sed eget faucibus sem, sit amet gravida eros. " "Mauris mollis velit sit amet blandit faucibus. Nullam laoreet arcu viverra mi maximus, " "quis cursus purus imperdiet." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " "Ut at sem id tortor interdum facilisis. Donec orci tortor, ultrices sed dui nec, " "sollicitudin egestas ante. Sed eget faucibus sem, sit amet gravida eros. " "Mauris mollis velit sit amet blandit faucibus. Nullam laoreet arcu viverra mi maximus, " "quis cursus purus imperdiet." ) self.summary_label.setWordWrap(True) self.summary_label.setStyleSheet( "background-color: #333333; color: #FFFFFF; padding: 5px; " "border-radius: 5px; font-size: 20px;" ) # Body label self.body_label = QLabel("Shorter body text for testing.", self) self.body_label.setWordWrap(True) self.body_label.setStyleSheet( "background-color: #444444; color: #FFFFFF; padding: 5px; border-radius: 5px;" ) # Add widgets to layout with stretch factors self.main_layout.addWidget(self.summary_label) self.main_layout.addWidget(self.body_label) if __name__ == "__main__": app = QApplication(sys.argv) window = TestWindow() window.show() sys.exit(app.exec_())