Issue with QLabel and wordwrap
-
Hi,
I'm currently facing an issue where I'm struggling to correctly size a QLabel that has word-wrap enabled.
Feels like I tried everything and I can't find an acceptable outcome.
This QLabel is in a QHBoxLayout that contains the checkbox visual and the QLabel.
I've painted the QLabel red in order to make it more visible.Here is what we currently have:

The problem is that the QLabel spreads horizontally and take all the available space. It wouldn't be an issue if not for the fact that this QLabel reacts to mouse clicks, thus making the entire red section clickable. Only the section with the actual text should be clickable.
No matter what I try (different sizePolicies, adding an empty widget with various stretch factors...), I can only ever get this result:

If I remove the word-wrap then I actually get what I want :

But I can't remove the word-wrap, we must have it on.
I'm starting to think that there is no way to do what I want without removing the word-wrap, if that's the case then so be it it, but if someone here has any ideas, I'm interested.
Cordially, PLL3.
-
Hi,
I'm currently facing an issue where I'm struggling to correctly size a QLabel that has word-wrap enabled.
Feels like I tried everything and I can't find an acceptable outcome.
This QLabel is in a QHBoxLayout that contains the checkbox visual and the QLabel.
I've painted the QLabel red in order to make it more visible.Here is what we currently have:

The problem is that the QLabel spreads horizontally and take all the available space. It wouldn't be an issue if not for the fact that this QLabel reacts to mouse clicks, thus making the entire red section clickable. Only the section with the actual text should be clickable.
No matter what I try (different sizePolicies, adding an empty widget with various stretch factors...), I can only ever get this result:

If I remove the word-wrap then I actually get what I want :

But I can't remove the word-wrap, we must have it on.
I'm starting to think that there is no way to do what I want without removing the word-wrap, if that's the case then so be it it, but if someone here has any ideas, I'm interested.
Cordially, PLL3.
@PLL3 You could use https://doc.qt.io/qt-6/qfontmetrics.html#boundingRect-1 to calculate the minimum size of the label with given text
-
Something that may help as a work-around, IIRC QLabel text can support basic HTML markup so you could maybe manually insert <br> tags where you want it wrapped?
OK...my bad...I misread OP. I'm not understanding why you cannot use the proper layout constraints to achieve what you seek. If they are not good enough then go brute force and derive your own QLabel from QWidget and manually paint the box from a pixmap or whatever.
I'm also not understanding the cart-blanc statement about "we must have it on": stupid internal policy or technical reason?
-
Something that may help as a work-around, IIRC QLabel text can support basic HTML markup so you could maybe manually insert <br> tags where you want it wrapped?
OK...my bad...I misread OP. I'm not understanding why you cannot use the proper layout constraints to achieve what you seek. If they are not good enough then go brute force and derive your own QLabel from QWidget and manually paint the box from a pixmap or whatever.
I'm also not understanding the cart-blanc statement about "we must have it on": stupid internal policy or technical reason?
@Kent-Dorfman
I think the problem for the OP here is that without word wrap aQLabelterminates at the end of the text while it appears from what they show that once you switch word wrap on (which they need) it makes it wide automatically, wider than it needs to be. At least that is what they are showing in the pics. -
Yes, the horizontal size hint of QLabel with wordWrap on is such a pain in the a**. I end up writing my own label class.
Emmm...but your problem is a bit different from mine. So visually you could accept picture 1, but you need only reacting to the text part's clicking, right?
Then you could try the html markup way, and make your text in<a href="xxx"></a>tags ("xxx" cannot be empty and need adding style to make links look like normal text), then react toQLabel::linkActivatedinstead of click events. But this will make the cursor becoming hand when hovering the text, if you don't want this you need to also connectQWidget::unsetCursortoQLabel::linkHovered.
Another way would be trying to get the text rect in the label and ignore the click events outside text rect, but this can be more complicated. -
Thinking about it, my initial feeling is that --- assuming the OP is correct that word wrap makes the one line label grow to full width, which I have not verified --- this is "wrong" in Qt. Why should word wrap make that be the case? I can sort of guess that it helps Qt calculate the wrapping, but that is not the point. Or does someone have a reason why it is "correct"?
-
Hi,
I'm currently facing an issue where I'm struggling to correctly size a QLabel that has word-wrap enabled.
Feels like I tried everything and I can't find an acceptable outcome.
This QLabel is in a QHBoxLayout that contains the checkbox visual and the QLabel.
I've painted the QLabel red in order to make it more visible.Here is what we currently have:

The problem is that the QLabel spreads horizontally and take all the available space. It wouldn't be an issue if not for the fact that this QLabel reacts to mouse clicks, thus making the entire red section clickable. Only the section with the actual text should be clickable.
No matter what I try (different sizePolicies, adding an empty widget with various stretch factors...), I can only ever get this result:

If I remove the word-wrap then I actually get what I want :

But I can't remove the word-wrap, we must have it on.
I'm starting to think that there is no way to do what I want without removing the word-wrap, if that's the case then so be it it, but if someone here has any ideas, I'm interested.
Cordially, PLL3.
@PLL3
I have now had a go with some code which may (or may not) emulate what you are doing:#include <QApplication> #include <QCheckBox> #include <QHBoxLayout> #include <QLabel> #include <QVBoxLayout> #include <QWidget> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; w.setGeometry(200, 200, 400, 400); QVBoxLayout *vlayout = new QVBoxLayout; w.setLayout(vlayout); QHBoxLayout *hlayout = new QHBoxLayout; vlayout->addLayout(hlayout); vlayout->addStretch(1); QCheckBox *cb = new QCheckBox; hlayout->addWidget(cb); QLabel *lab = new QLabel("This is the first line."); lab->setStyleSheet("QLabel { background-color : red; }"); hlayout->addWidget(lab); // hlayout->addStretch(1); // lab->setWordWrap(true); w.show(); return a.exec(); }Try with & without the
hlayout->addStretch(1);commented out or included. That controls where the label appears in the line and also whether it "extends" or "terminates" at the end of the text. But in both cases I do not find that thelab->setWordWrap(true);affects the layout/size of the label. Qt 6.4.2 supplied with Ubuntu 24.04. So what minimal example do you have for your behaviour? This is why we always request a small example of code :) -
Thinking about it, my initial feeling is that --- assuming the OP is correct that word wrap makes the one line label grow to full width, which I have not verified --- this is "wrong" in Qt. Why should word wrap make that be the case? I can sort of guess that it helps Qt calculate the wrapping, but that is not the point. Or does someone have a reason why it is "correct"?
@JonB It is not like that. The situation is, for example we have a QLabel with this text "Install all additional resources", the size hint when wordWrap=false is (174, 15). But if wordWrap=true, then the size hint changes to (113, 30), so if it is put in a layout that calculate its size according to the size hint, then it will be break into at least two lines even if the space is enough for single line.
Edit: Ah, your example code doesn't have enough long text, try the above text, I can see it on Windows. -
@JonB It is not like that. The situation is, for example we have a QLabel with this text "Install all additional resources", the size hint when wordWrap=false is (174, 15). But if wordWrap=true, then the size hint changes to (113, 30), so if it is put in a layout that calculate its size according to the size hint, then it will be break into at least two lines even if the space is enough for single line.
Edit: Ah, your example code doesn't have enough long text, try the above text, I can see it on Windows.@Bonnie
Sorry, I don't follow at all. I have provided minimal code and described what I see, so I don't know what "It is not like that" means?Edit: Ah, your example code doesn't have enough long text, try the above one, I can see it on Windows.
Still not sure what to try. I have changed my text to
Install all additional resourcesand I agree it wraps --- to 2 lines. But I never see the very original

Could you tell me exactly what to try, please?
-
@Bonnie
Sorry, I don't follow at all. I have provided minimal code and described what I see, so I don't know what "It is not like that" means?Edit: Ah, your example code doesn't have enough long text, try the above one, I can see it on Windows.
Still not sure what to try. I have changed my text to
Install all additional resourcesand I agree it wraps --- to 2 lines. But I never see the very original

Could you tell me exactly what to try, please?
-
@JonB This picture does not have any layout problem. I think OP set the horizontal size policy of the label to expanding. So the width is not set according to its size hint.
@Bonnie
I am still lost! If I understand you right, I kepthlayout->addStretch(1);commented out and instead addedlab->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);, right? Then I do see the original withoutlab->setWordWrap(true)as per the first pic taking up the full width, but when I add in word wrap it makes no difference and still fills the full width (not wraps to subsequent lines)...? -
@Bonnie
I am still lost! If I understand you right, I kepthlayout->addStretch(1);commented out and instead addedlab->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);, right? Then I do see the original withoutlab->setWordWrap(true)as per the first pic taking up the full width, but when I add in word wrap it makes no difference and still fills the full width (not wraps to subsequent lines)...?@JonB Apologies, my "It is not like that" means "word wrap makes the one line label grow to full width" is not the thing.
In the first picture OP have a left checkbox with prefered width and a right label (wordWrap=true) with expanding width. What it shows meets OP's expect (I think), but then he has some problems with the click events, so he want the label to not have any empty space, using other things to fill the space, like an empty widget or spacer.
So in the second picture, the label is not expanding anymore and there's expanding empty space (widget or spacer) on the right.
But after putting expanding empty widget or spacer, the label will break into lines, that's not what OP wants. -
@JonB Apologies, my "It is not like that" means "word wrap makes the one line label grow to full width" is not the thing.
In the first picture OP have a left checkbox with prefered width and a right label (wordWrap=true) with expanding width. What it shows meets OP's expect (I think), but then he has some problems with the click events, so he want the label to not have any empty space, using other things to fill the space, like an empty widget or spacer.
So in the second picture, the label is not expanding anymore and there's expanding empty space (widget or spacer) on the right.
But after putting expanding empty widget or spacer, the label will break into lines, that's not what OP wants.@Bonnie
Hmm. I still don't 100% follow [I am going to create my own brand new post about layouts and spacing in a few moments to ask about what I have never understood, but that may be a separate matter]. But if I understand you right you are saying when the OP wrote "If I remove the word-wrap then I actually get what I want :" that is not "the whole story", they have made some other change(s) than just word wrap (e.g. expanding policy, spacer/stretch)?Anyway at this point for my own part as I wrote earlier I would want the OP to post exactly what they have done to see what they see....
-
@Bonnie
Hmm. I still don't 100% follow [I am going to create my own brand new post about layouts and spacing in a few moments to ask about what I have never understood, but that may be a separate matter]. But if I understand you right you are saying when the OP wrote "If I remove the word-wrap then I actually get what I want :" that is not "the whole story", they have made some other change(s) than just word wrap (e.g. expanding policy, spacer/stretch)?Anyway at this point for my own part as I wrote earlier I would want the OP to post exactly what they have done to see what they see....
@JonB said in Issue with QLabel and worwrap:
But if I understand you right you are saying when the OP wrote "If I remove the word-wrap then I actually get what I want :" that is not "the whole story", they have made some other change(s) than just word wrap (e.g. expanding policy, spacer/stretch)?
Emm, I think this is talking about the second picture and the third picture, the only difference between these two is in the third picture wordWrap is changed to false.
(Now I'm not sure if I understand you right, what does "the one line label grow to full width" mean).
I've met similar problem but not the same as OP. I could give a simple example by changing your code to
QVBoxLayout *vlayout = new QVBoxLayout; w.setLayout(vlayout); QLabel *lab = new QLabel("Install all additional resources"); lab->setStyleSheet("QLabel { background-color : red; }"); vlayout->addWidget(lab, 0, Qt::AlignCenter); lab->setWordWrap(true);So I want this label to be in the center of its parent widget which has a fixed (or maximum) width, and when the text is too long and can't be shown in single line completely, it should wrap. (This is exactly how our UI designs it)
But if wordwrap=true, it breaks into 2 lines even though there's enough space to show it in single line. -
Hi everyone, just logged in and there's alot of activity ! Did not expect that.
I haven't had the time to read everything here, but in the meantime I feel like some more context is warranted:
This whole thing is a custom class of mine mimicking a QCheckBox, it is very simply, a QSvgWidget and a QLabel put together in a QHBoxLayout with some signal/slot and events shenanigans to make it interactive.
This was made to add the word-wrap property to QCheckBoxes, which for some reasons isn't available in base QCheckBox. This whole thing was made for the word-wrap hence why I can't remove it. And we need word-wrap because our app is "modular" so to speak, I'm not in control of the text, and depending on the content and the language, it could get pretty long and need a word-wrap.
As requested, here is a simple reproductible example:
Subwidget.cpp:
SubWidget::SubWidget(QWidget *parent) : QWidget{parent} { QSvgWidget * svg = new QSvgWidget("Path/to/the/SVG/asset/Not/really/relevant"); QVBoxLayout * innerLayout = new QVBoxLayout(); innerLayout->setContentsMargins(0, 0, 0, 0); innerLayout->setSpacing(0); innerLayout->addWidget(svg); QFrame * frame = new QFrame(); frame->setStyleSheet("QFrame{min-width: 14px;max-width: 14px;min-height: 14px;max-height: 14px;margin:0px;padding:0px;}"); frame->setLayout(innerLayout); QLabel * label = new QLabel("This is a text, a very looong text !!!!"); label->setWordWrap(true); label->setStyleSheet("QLabel{background-color:red;margin:0px;pading:0px}"); QHBoxLayout * layout = new QHBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(frame); layout->addWidget(label); this->setLayout(layout); }- The QSvgWidget has to be in a QFrame, because for some reasons defining the size of a QSvgWidget in the stylesheet causes some wonky behaviour but I found that wrapping it in a QFrame solves my problems
and main.cpp
#include "SubWidget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); SubWidget w; w.show(); return a.exec(); }and the .pro file:
QT += core gui widgets svgwidgets CONFIG += c++17 SOURCES += \ SubWidget.cpp \ main.cpp HEADERS += \ SubWidget.h # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += targetHere's the result:

and once stretched:

All I'm trying to do is make it so that the QLabel (the red zone) stops after the end of the text once stretched.
I'll take a more detailed look into what has been proposed and I'll keep you updated.
EDIT: @JonB you said
assuming the OP is correct that word wrap makes the one line label grow to full width, which I have not verifiedDo note that in my example, the QLabel gets stretched horizontally even if word-wrap is turned off (but fixing that becomes trivial by adding some stretch factors here and there), so I'm a bit confused.
-
Yes, the horizontal size hint of QLabel with wordWrap on is such a pain in the a**. I end up writing my own label class.
Emmm...but your problem is a bit different from mine. So visually you could accept picture 1, but you need only reacting to the text part's clicking, right?
Then you could try the html markup way, and make your text in<a href="xxx"></a>tags ("xxx" cannot be empty and need adding style to make links look like normal text), then react toQLabel::linkActivatedinstead of click events. But this will make the cursor becoming hand when hovering the text, if you don't want this you need to also connectQWidget::unsetCursortoQLabel::linkHovered.
Another way would be trying to get the text rect in the label and ignore the click events outside text rect, but this can be more complicated.Using this html markup tech looks like an easy solution for my issue (at least easier than manually calculating the rect and dealing with mouse events that way).
Alas this would open us up for some code injection, since the text in those labels is loaded at run-time from some on-disk files, so this solution is a no-go sadly. -
Some additional infos:
In my OG post, this first image is our current implementation.

This second image is after calling QHBoxLayout::addStretch(100) on our layout after adding our checkbox and label:

And the third image is exact same setup as the second, but without word-wrap:

Which is exactly what I'm looking for, but with word-wrap obviously.
Glad to see I'm not the only one having some issues with word-wrap, even though I never had issues with labels wrapping when not needed.
-
Using this html markup tech looks like an easy solution for my issue (at least easier than manually calculating the rect and dealing with mouse events that way).
Alas this would open us up for some code injection, since the text in those labels is loaded at run-time from some on-disk files, so this solution is a no-go sadly.@PLL3 said in Issue with QLabel and worwrap:
Using this html markup tech looks like an easy solution for my issue (at least easier than manually calculating the rect and dealing with mouse events that way).
Alas this would open us up for some code injection, since the text in those labels is loaded at run-time from some on-disk files, so this solution is a no-go sadly.Well it should be safe if you handle the text by
QString::toHtmlEscaped().
But I actually don't like that the cursor needs to be unset when hovering.
So I think the mouse events filtering may be a better way.
Aren't you already handling the mouse events since QLabel has no "clicked" signal?@PLL3 said in Issue with QLabel and worwrap:
Glad to see I'm not the only one having some issues with word-wrap, even though I never had issues with labels wrapping when not needed.
This unnecessarily breaking lines issue only occurs when the sizehint width is used as the actual label width.
In normal case, long text labels are usually horizontally expanding, so there won't be such problem.
I never had such issues until my current project. -
Aren't you already handling the mouse events since QLabel has no "clicked" signal?
Yes, but to handle the mouse position I simply use the enterEvent and leaveEvent toggling a flag to remember wether the mouse is hovering the widget or no.
If I understand correctly, I'll have to replace/modify that to work with the text rect instead of the whole QLabel, sounds doable, if only a bit convoluted.Anyway, I think we've pretty much gone round the whole subject. Nothing much to do here, I think I'll close the thread soon.
I'll keep watching @JonB 's thread, since it's asking for an evolution that would solve my current issue. -
Hi, closing this thread.
To sum up, my issue stems from a Qt layout limitation, for posterity's sake here's the solution that I ended up using to get around my problem:
I installed an eventFilter on my QLabel, filtering for QSinglePointEvent and checking wether the cursor was within the text, here's a small code example:
bool SubWidget::eventFilter(QObject * iObject, QEvent* iEvent){ if ((iObject == _label) && (iEvent->isSinglePointEvent())){ //if event is a mouse event on _label QFontMetrics fm(_label->font()); int textWidth = fm.horizontalAdvance(_label->text()); // width of the text in pixels int textHeight = fm.height(); // height of the text in pixels int textX = 0; int textY = 0; // calculate the coordinates for the top-left pixel of the actual text, text position depends on alignment if ((_label->alignment() & Qt::AlignLeft) == Qt::AlignLeft){ textX = _label->x(); } else if ((_label->alignment() & Qt::AlignHCenter) == Qt::AlignHCenter){ textX = _label->x() + (_label->width() - textWidth)/2; } else if ((_label->alignment() & Qt::AlignRight) == Qt::AlignRight){ textX = _label->x() + _label->width() - textWidth; } if ((_label->alignment() & Qt::AlignTop) == Qt::AlignTop){ textY = _label->y(); } else if ((_label->alignment() & Qt::AlignVCenter) == Qt::AlignVCenter){ textY = _label->y() + (_label->height() - textHeight)/2; } else if ((_label->alignment() & Qt::AlignBottom) == Qt::AlignBottom){ textY = _label->y() + _label->height() - textHeight; } QSinglePointEvent* pointEvent = static_cast<QSinglePointEvent*>(iEvent); QPointF mousePos = pointEvent->position(); // Get mouse position relative to the label from the event if ((textX <= mousePos.x() && mousePos.x() <= (textX + textWidth)) // if mouse is located within the text area && (textY <= mousePos.y() && mousePos.y() <= (textY + textHeight))) { //Do stuff here to further refine the event //eg: hover event, mousepress event etc etc return true; } else { return false; } } return QWidget::eventFilter(iObject, iEvent); } -
P PLL3 has marked this topic as solved on