Main question
Main question

Reputation: 45

How to prevent QLabel from expanding due to text inside?

Essence in the following, in the form there is QScrollArea in which there is QWidget. In this widget, I add dynamic frames filled with some information about the contact person - full name, phone number, email, description. It looks like this (below):

enter image description here

Everything looks quite adequate, but if any of the fields is made long enough - for example, full name + description - then the size of the QLabel expands immediately, crossing all boundaries

enter image description here

But that's okay, nonsense starts there, when the size and full name and descriptions are quite long - everything breaks down there. QLabel size Not limited by the size allocated to them in the Widget, they expand the entire ScrollArea, hiding all text that doesn't fit:

enter image description here

I'm already tired of combining different combinations of SizePolicy, how can I limit the size of either the entire ScrollArea so that it does not go beyond the scope, or the size of the QLabel itself, so that if the text in this label is longer than the space allocated to this label, it will not expand, but just hide the text.

UPD. You can achieve "APPROXIMATELY" the behavior I need if you turn on this checkbox (again, I came to this by typing):

enter image description here


enter image description here

However, then the entire ScrollArea stops expanding, which is also not a good solution. In general, help me out, people, what needs to be done in order to select the frame / widget / QScrollArea settings I need so that the text does not crawl out of the QLabel size, indicated not by the text inside, but by the factors surrounding it.

Roughly speaking, I need to either limit the size of the QLabel so that it does not change with the change of the text inside, but solely due to external factors (expanded the window - it increased, made a long text - it was cut off). Or you need to somehow disable any expansion of QScrollArea.

Upvotes: 0

Views: 679

Answers (1)

Vadim Tsybin
Vadim Tsybin

Reputation: 11

I faced the same issue and in the end I decided to replace QLabel with read-only QLineEdit

l = QLineEdit()
l.setReadOnly(True)

If you absolutely have to use QLabel, then options to consider:

You can try to enable text wrapping. It will increase the vertical size though and will not work if there is long word (exceeding space for the widget) in the text

l = QLabel()
l.setWordWrap(True)

You can try to trim the text before setText(). It requires to figure out pixel size of text and available space for it in QLabel. There are good posts on this method: PySide/PyQt truncate text in QLabel based on minimumSize and Qt - How to get the pixel length of a string in a QLabel?

Note: Examples above are in Python but it should be easy enough to convert to C++

Upvotes: 0

Related Questions