Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct


    Qt World Summit: Early-Bird Tickets

    QPlainTextEdit Set Height Based on Text Pasted In

    General and Desktop
    1
    2
    1316
    Loading More Posts
    • 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.
    • A
      aronx69 last edited by

      I've derived a class from QPlainTextEdit and connected a slot to the underlying QTextDocument's contentsChanged() signal. What I'm trying to do is auto-size the height of the editor based on the contents. This code accomplishes the auto height...

      @int lineCount = this->document()->lineCount() + 2;
      QFontMetrics fm(this->font());
      int lineSpacing = fm.lineSpacing();
      int height = lineCount * lineSpacing + this->TopMargin() + this->BottomMargin();

      this->setFixedHeight(height);@

      (NOTE: this won't work for QTextEdit, because the lineCount equals the paragraph count, unless you're using a custom layout.)

      The code works great when the user is editing the text. The problems occur when text is pasted in. It seems it takes a while for the lineCount to situate to the contents. If I call this method multiple times within the same signal, the lineCount increases each pass. So it's almost as if the QTextDocument's layout is running in a separate thread which doesn't finish laying out the pasted in text before the contentsChanged signal is generated.

      Any thoughts or suggestions? Is there a better signal to connect to?

      I've looked through the docs and can't find a "finishedLayingOut" signal or something that indicates the lineCount is completely updated.

      1 Reply Last reply Reply Quote 1
      • A
        aronx69 last edited by

        I think I found a suitable solution. I just overrode the paintEvent() and calculated the height there. Seems to work great.

        1 Reply Last reply Reply Quote 1
        • First post
          Last post