[Solved]Limit number of characters in QTextEdit

  • Well, I need to limit the number of characters in a QTextEdit. I found something that says to rewrite the keyPressEvent and enter a event filter. I was thinking of something like

    @if(textEdit->document()->characterCount() >= maxLen) {
    limit the editing only for delete, up, down, etc.
    } else {
    normal editing

    The problem is that I am not sure on how to implement this. On the else I just copy from the normal keyPressEvent. I know I can use QLineEdit but I need a multiline text editor. Also it will only contain plain text (no html subset).

  • Sorry for necroposting, but i have a better way than reimplementing keyPress.

    void wClassArea::on_textEdit_textChanged()
    if(ui->textEdit->toPlainText().length() > m_maxDescriptionLength)
    int diff = ui->textEdit->toPlainText().length() - m_maxTextEditLength; //m_maxTextEditLength - just an integer
    QString newStr = ui->textEdit->toPlainText();
    QTextCursor cursor(ui->textEdit->textCursor());
    cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);

    There we do:

    1. Catch textChanged event.
    2. Compare length of the text in TextEdit buffer with our limit. It is vital, because when you paste even large text (millions of chars), you will get there only i time. I have checked this in the debug mode.
    3. Get text string from TextEdit.
    4. Remove all symbols over limit.
    5. Move cursor to the end.

    P.s. I just didn't want to inherit QTextEdit and change my old code.-)
    P.p.s. sorry for my English.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.