[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).
-
found an example that works just fine:
http://qt-project.org/faq/answer/how_can_i_get_set_the_max_length_of_a_qtextedit
-
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();
newStr.chop(diff);
ui->textEdit->setText(newStr);
QTextCursor cursor(ui->textEdit->textCursor());
cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
ui->textEdit->setTextCursor(cursor);
}
}There we do:
- Catch textChanged event.
- 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.
- Get text string from TextEdit.
- Remove all symbols over limit.
- 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.