本文介绍了pyqt4 QTextEdit - 如何设置MaxLength?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与数据库 VARCHAR(2048) 字段相关联的多行 QTextEdit.

I have a multi-line QTextEdit that is tied to database VARCHAR(2048) field.

我想将用户条目长度限制为最多 2048 个字符

I want to limit the user entry length to max of 2048 chars

QTextEdit 没有像 QLineEdit 那样的 setMaxLength(int) 方法.

QTextEdit does not have a setMaxLength(int) method like QLineEdit does.

大家有什么建议吗?

self.editBox = QTextEdit()

谢谢

推荐答案

我发现了 thisQt Wiki 上的常见问题解答:

没有直接的 API 来设置/获取 QTextEdit 的最大长度,但您可以通过将插槽连接到 contentsChanged() 信号,然后调用 toPlainText().length() 找出它有多大.如果达到了限制,那么您可以重新实现 keyPressEvent()keyReleaseEvent() 对普通字符不做任何处理.

您可能还对这篇文章感兴趣附有一些代码(希望它对你有用):

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

这篇关于pyqt4 QTextEdit - 如何设置MaxLength?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-31 05:59