Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Issue with QLabel and wordwrap
Qt 6.11 is out! See what's new in the release blog

Issue with QLabel and wordwrap

Scheduled Pinned Locked Moved Solved General and Desktop
27 Posts 6 Posters 17.4k Views 3 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • PLL3P Offline
    PLL3P Offline
    PLL3
    wrote on last edited by aha_1980
    #1

    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:
    2c60300e-32bf-43ef-86db-1b906cb59ea5-image.png

    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:
    1723246d-768b-4824-b6b6-1a0529f44731-image.png

    If I remove the word-wrap then I actually get what I want :
    8bc48067-be62-42c9-8c81-8597820a1789-image.png

    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.

    jsulmJ JonBJ 2 Replies Last reply
    0
    • PLL3P 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:
      2c60300e-32bf-43ef-86db-1b906cb59ea5-image.png

      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:
      1723246d-768b-4824-b6b6-1a0529f44731-image.png

      If I remove the word-wrap then I actually get what I want :
      8bc48067-be62-42c9-8c81-8597820a1789-image.png

      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.

      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on last edited by
      #2

      @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

      https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      0
      • Kent-DorfmanK Offline
        Kent-DorfmanK Offline
        Kent-Dorfman
        wrote on last edited by Kent-Dorfman
        #3

        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?

        The dystopian literature that served as a warning in my youth has become an instruction manual in my elder years.

        JonBJ 1 Reply Last reply
        0
        • Kent-DorfmanK Kent-Dorfman

          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?

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by
          #4

          @Kent-Dorfman
          I think the problem for the OP here is that without word wrap a QLabel terminates 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.

          1 Reply Last reply
          0
          • B Offline
            B Offline
            Bonnie
            wrote on last edited by Bonnie
            #5

            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 to QLabel::linkActivated instead 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 connect QWidget::unsetCursor to QLabel::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.

            PLL3P 1 Reply Last reply
            0
            • JonBJ Offline
              JonBJ Offline
              JonB
              wrote on last edited by
              #6

              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"?

              B 1 Reply Last reply
              0
              • PLL3P 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:
                2c60300e-32bf-43ef-86db-1b906cb59ea5-image.png

                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:
                1723246d-768b-4824-b6b6-1a0529f44731-image.png

                If I remove the word-wrap then I actually get what I want :
                8bc48067-be62-42c9-8c81-8597820a1789-image.png

                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.

                JonBJ Offline
                JonBJ Offline
                JonB
                wrote on last edited by
                #7

                @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 the lab->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 :)

                1 Reply Last reply
                0
                • JonBJ JonB

                  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"?

                  B Offline
                  B Offline
                  Bonnie
                  wrote on last edited by Bonnie
                  #8

                  @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.

                  JonBJ 1 Reply Last reply
                  0
                  • B Bonnie

                    @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.

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by JonB
                    #9

                    @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 resources and I agree it wraps --- to 2 lines. But I never see the very original
                    49c9950c-2f4f-4090-b92f-fa81e2583480-image.png

                    Could you tell me exactly what to try, please?

                    B 1 Reply Last reply
                    0
                    • JonBJ JonB

                      @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 resources and I agree it wraps --- to 2 lines. But I never see the very original
                      49c9950c-2f4f-4090-b92f-fa81e2583480-image.png

                      Could you tell me exactly what to try, please?

                      B Offline
                      B Offline
                      Bonnie
                      wrote on last edited by
                      #10

                      @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.

                      JonBJ 1 Reply Last reply
                      0
                      • B Bonnie

                        @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.

                        JonBJ Offline
                        JonBJ Offline
                        JonB
                        wrote on last edited by
                        #11

                        @Bonnie
                        I am still lost! If I understand you right, I kept hlayout->addStretch(1); commented out and instead added lab->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);, right? Then I do see the original without lab->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)...?

                        B 1 Reply Last reply
                        0
                        • JonBJ JonB

                          @Bonnie
                          I am still lost! If I understand you right, I kept hlayout->addStretch(1); commented out and instead added lab->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);, right? Then I do see the original without lab->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)...?

                          B Offline
                          B Offline
                          Bonnie
                          wrote on last edited by Bonnie
                          #12

                          @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.

                          JonBJ 1 Reply Last reply
                          0
                          • B Bonnie

                            @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.

                            JonBJ Offline
                            JonBJ Offline
                            JonB
                            wrote on last edited by JonB
                            #13

                            @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....

                            B 1 Reply Last reply
                            0
                            • JonBJ JonB

                              @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....

                              B Offline
                              B Offline
                              Bonnie
                              wrote on last edited by Bonnie
                              #14

                              @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.

                              1 Reply Last reply
                              0
                              • PLL3P Offline
                                PLL3P Offline
                                PLL3
                                wrote on last edited by PLL3
                                #15

                                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 += target
                                

                                Here's the result:
                                b90e2bc3-37d9-49ac-bc88-34ef5559ce41-image.png

                                and once stretched:
                                a13a14ba-5cc3-468a-b453-03c2dfd64799-image.png

                                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 verified

                                Do 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.

                                1 Reply Last reply
                                0
                                • B Bonnie

                                  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 to QLabel::linkActivated instead 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 connect QWidget::unsetCursor to QLabel::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.

                                  PLL3P Offline
                                  PLL3P Offline
                                  PLL3
                                  wrote on last edited by
                                  #16

                                  @Bonnie

                                  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.

                                  B 1 Reply Last reply
                                  0
                                  • PLL3P Offline
                                    PLL3P Offline
                                    PLL3
                                    wrote on last edited by
                                    #17

                                    Some additional infos:

                                    In my OG post, this first image is our current implementation.
                                    image.png

                                    This second image is after calling QHBoxLayout::addStretch(100) on our layout after adding our checkbox and label:
                                    5334d6cc-5511-485a-b205-bf4f88f7bf87-image.png

                                    And the third image is exact same setup as the second, but without word-wrap:
                                    9f93a92d-55d9-4b2a-afaa-92f9f758f7f4-image.png

                                    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.

                                    1 Reply Last reply
                                    0
                                    • PLL3P PLL3

                                      @Bonnie

                                      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.

                                      B Offline
                                      B Offline
                                      Bonnie
                                      wrote on last edited by Bonnie
                                      #18

                                      @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.

                                      1 Reply Last reply
                                      0
                                      • PLL3P Offline
                                        PLL3P Offline
                                        PLL3
                                        wrote on last edited by
                                        #19

                                        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.

                                        JonBJ 1 Reply Last reply
                                        0
                                        • PLL3P Offline
                                          PLL3P Offline
                                          PLL3
                                          wrote on last edited by PLL3
                                          #20

                                          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);
                                          }
                                          
                                          B 1 Reply Last reply
                                          0
                                          • PLL3P PLL3 has marked this topic as solved on

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved