Quick Tip: Limit Character Count in a QTextEdit

I can think of many instances of where you would want to limit the character count of a text edit. Just recently I used it to keep people from overfilling a field for a database (very important!), but there are several other, practical ways to use this. The code:

    // If the length is greater than 300 characters
    if (ui->plainTextEdit->toPlainText().length() > 300)
        QString text = ui->plainTextEdit->toPlainText();
        text.chop(text.length() - 300); // Cut off at 300 characters
        ui->plainTextEdit->setPlainText(text); // Reset text

        // This code just resets the cursor back to the end position
        // If you don't use this, it moves back to the beginning.
        // This is helpful for really long text edits where you might
        // lose your place.
        QTextCursor cursor = ui->plainTextEdit->textCursor();
        cursor.setPosition(ui->plainTextEdit->document()->characterCount() - 1);

        // This is your "action" to alert the user. I'd suggest something more
        // subtle though, or just not doing anything at all.
                              "Please be sure that you keep the description under 300 characters.");

The best place to put this would be in the textChanged() signal so it checks every time the user updates the text edit. You could also insert it before, say, writing the text out to a file.


4 thoughts on “Quick Tip: Limit Character Count in a QTextEdit

  1. Pingback: [ISTC/Qt] QTextEdit Limit Number of Characters | Quarbby

    1. TheMachine Post author

      That’s a good question. I wrote this code for a line edit where I anticipated people would hit the max at the end. You could modify the line that sets the cursor position to place the cursor in the middle of the text where the user was typing.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s