PDA

View Full Version : Text edit and maxLength



vieraci
29th April 2007, 12:24
Can text edit widget have maxLength like the line edit widget ?

marcel
29th April 2007, 12:34
No, but you can count the characters in it when the textChanged() signal is emitted and disable the input if the count reaches a certain limit.

Regards

vermarajeev
30th April 2007, 04:04
No, but you can count the characters in it when the textChanged() signal is emitted and disable the input if the count reaches a certain limit.

Regards

The other option would be to filter the event on TextEdit and checking QString(textEdit->text).length() to certain MAX limit.

Thanks

oscar
19th September 2008, 18:12
Just for convenience, here is an example of a QTextEdit child class implementing the missing maxLength feature.

Regards,
Oscar



#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::toPla inText().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"));
}
}

enrique.fe
6th December 2011, 01:43
It works!

int maximum = 500;
if (ui.textEdit->toPlainText().length() > maximum) {
ui.textEdit->textCursor().deletePreviousChar();
}