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
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"));
}
}