I need to display text with a QLabel with following requirements:
- Word wrapping
- Expand from small width to full width according to the length of the text while the label takes a single line
- Always full width while the label takes multiple lines
- Background of the label is filled with some color
I tried putting QLabel with sizePolicy (Preferred, Preferred) and QSpacerItem with sizePolicy (Expanding, Minimum) into QHBoxLayout.
And I expect that the text is not wrapped before reaches right side.
But I got that the text is wrapped before reaches right side.
How to prevent this unnecessary word-wrapping?
Reproduction code
Note
- If I do not put the spacer in the HBox, then meets requirement 1 and 3, but 2 (The area that text not exists is filled with background color. In this time, I do not want this behavior).
- If I disable word-wrapping, then meets requirement 2, but 1.
Relevant questions
This question is about the similar problem, but there is no layout.
QBoxLayout::setStretch
to determine how much space is given to each expanding item (e.g. set stretch=4 for label and 1 for spacer will give label 4/5 of full width). If other items in the layout are fixed-size, expanding label will take all available space. – Pavel Strakhov