3

I have a multi-line QTextEdit that is tied to database VARCHAR(2048) field.

I want to limit the user entry length to max of 2048 chars

QTextEdit does not have a setMaxLength(int) method like QLineEdit does.

Anyone have any suggestions?

self.editBox = QTextEdit()

Thanks

2 Answers 2

3

I found this FAQ on the Qt Wiki:

There is no direct API to set/get a maximum length of a QTextEdit, but you can handle this yourself by connecting a slot to the contentsChanged() signal and then call toPlainText().length() to find out how big it is. If it is up to the limit then you can reimplement keyPressEvent() and keyReleaseEvent() to do nothing for normal characters.

You may also be interested in this post which has some code attached (hopefully it works for you):

#include <QtCore>
#include <QtGui>
#include "TextEdit.hpp"

TextEdit::TextEdit() : QPlainTextEdit() {
connect(this, SIGNAL(textChanged()), this, SLOT(myTextChanged()));
}

TextEdit::TextEdit(int maxChar) : QPlainTextEdit() {
this->maxChar = maxChar;
connect(this, SIGNAL(textChanged()), this, SLOT(myTextChanged()));
}

int TextEdit::getMaxChar() {
return maxChar;
}

void TextEdit::setMaxChar(int maxChar) {
this->maxChar = maxChar;
}

void TextEdit::myTextChanged() {
if (QPlainTextEdit::toPlainText().length()>maxChar) {
QPlainTextEdit::setPlainText(QPlainTextEdit::toPlainText().left(QPlainTextEdit::toPlainText().length()-1));
QPlainTextEdit::moveCursor(QTextCursor::End);
QMessageBox::information(NULL, QString::fromUtf8("Warning"),
QString::fromUtf8("Warning: no more then ") + QString::number(maxChar) + QString::fromUtf8(" characters in this field"),
QString::fromUtf8("Ok"));
}
}
1

Using the slot "textChanged()":

txtInput = QPlainTextEdit()

QObject.connect(txtInput, SIGNAL("textChanged()"), txtInputChanged)

def txtInputChanged():
    if txtInput.toPlainText().length() > maxInputLen:
        text = txtInput.toPlainText()
        text = text[:maxInputLen]
        txtInput.setPlainText(text)

        cursor = txtInput.textCursor()
    cursor.setPosition(maxInputLen)
    txtInput.setTextCursor(cursor)

Another possibility is to derive from "QPlainTextEdit" and reimplement the "keyPress" event filtering keys when maximum length is reached or other keys are pressed whose input is not desired.

http://doc.qt.io/qt-5/qplaintextedit.html#keyPressEvent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.