python - pyqt4 QTextEdit - 如何设置最大长度?

标签 python pyqt pyqt4

我有一个绑定(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/

相关文章:

pyqt - 从 PIL 到 PySide QImage 的更好方法?

python - 这段在 Pyqt 中创建 QPolygon 的代码正在停止我的应用程序!帮助?

Python-QTableWidget : How to catch signal when sorting in header is clicked

python - 如何使用 python 从给定文件中提取行 block

Python Qt QLineEdit 奇怪的编码

python - 更改 QTableWidget 单个单元格的可编辑性

python - 从 python 线程(不是主线程)启动 pyQt 线程有什么不好?

python - 在 python 中通过数据库正确调用和使用 Linux find

python - 如何在Python中将字符串列表中的元素添加到数组中

python - Tensorflow v1.10 +为什么在没有检查点的情况下需要输入服务接收器功能?