Qt World Summit: Submit your Presentation

Any suggestion on how to make floating QLabel move with content in QTextEdit?

  • I'd like to add image QLabel floating over a QTextEdit. The QLabel's rect is stored relative to the top of QTextEdit. When a line is added in the QTextEdit, the content in QTextEdit will move down, however the floating QLabel will not unless I do something about it. Can someone give me some idea how to deal with this? Can I anchor the QLabel to something on QTextEidt so it will move automatically when such anchor is moved due to editing in QTextEdit? Thank you.

  • Moderators


    there are multiple ways to do this.

    You say its "floating over the QTextEdit, is that by necessity? I mean has that an additional function. If not you can make it a child of QTextEdit and change the size Policy to autoadjust

    QLabel *overlayLabel = new QLabel(myTextEdit);
    //The label is created after the textedit, so it should lay on top but to make sure

    You could also subclass QTextEdit, catch the resizeEvent and emit a signal for your label, to change its own size accordingly.

  • @J.Hilk

    I just need to enable moving of the QLabel, so I guess I can make it a child of QTextEdit. So using your code and adding


    I put the QLabel somewhere in the middle of QTextEdit, however if I add a line above this label it does not move down. Am I missing something? Thanks.

  • Moderators

    maybe I ,missunderstood your question, what exactly is the purpose of your label and depending on what exactly should its position be?

  • I'm adding a label on top of QTextEdit to point to a certain content. I'd like it to move with such content so it will always point to the right thing. Thanks.

  • Moderators


    ok, thats a lot more complicated to realize.

    You need to detect when the Text of QTextEdit has changed, luckily QTextEdit has the Signal textChanged()

    In the Slot You'll to do some operations.
    Disclaimer: untested and/or pseudocode

       const QString s = textLabel->text();
       int x =0; int y = 0;
       //Check how many new lines are there before your target text and how many chars in the line
        for(QString sr : s.splitRef('\n')){
          x = sr.indexOf(targetText);
          if(x >=0)
    //Calculate  offset
      QFrontMetrix metrix(textLabel->font());
      y = y *metrix.height();
      x = x *metrix.averageCharWidth() ;
    //Move Label

  • @J.Hilk

    Thanks a lot!

  • Lifetime Qt Champion


    One alternative that might be simpler could be to subclass text edit and reimplement scrollContentsBy then you could update your table position with the help the delta provided.

    Hope it helps

Log in to reply