我有一个绑定(bind)到数据库 VARCHAR(2048) 字段的多行 QTextEdit。
我想将用户输入长度限制为最多 2048 个字符
QTextEdit 没有像 QLineEdit 那样的 setMaxLength(int) 方法。
有人有什么建议吗?
self.editBox = QTextEdit()
谢谢
最佳答案
我找到了 this FAQ在 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.
您可能还对 this post 感兴趣其中附有一些代码(希望对您有用):
#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"));
}
}
关于python - pyqt4 QTextEdit - 如何设置最大长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8479391/