QLineEdit :: maxLength支持Android

时间:2017-07-11 09:17:36

标签: android qt

我正在Android下部署Qt应用程序。如果QLineEdit长度有限(使用setMaxLength),则Android虚拟键盘会让我输入的字符数超过允许的数量,之后虚拟键盘关闭时QlineEdit内容会被截断。

#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QLineEdit>

int main( int argc, char* argv[] )
{
    QApplication app( argc, argv );    

    QMainWindow wnd;

    QLineEdit edit( &wnd );
    edit.setMaxLength( 10 );
    wnd.setCentralWidget( &edit );

    wnd.show();

    return app.exec();
}

有没有办法让虚拟键盘处理这个限制,不让用户输入多于允许的字符?

注意:创建了qt bug:https://bugreports.qt.io/browse/QTBUG-61940

1 个答案:

答案 0 :(得分:-1)

有不同的选择,第一个使用QLineEdit::setMaxLength功能。根据官方文件:

  

此属性包含文本的最大允许长度。如果   文本太长,在极限处被截断。

如果您在使用Android键盘时遇到问题,则可以使用QValidator使用给定QRegExp设置最大允许尺寸。为了您的目的,一个好的可能是:

/^(?=.{3,16}$)[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/

或者最简单的一个:

^\s*([^\s]\s*){0,400}$

值{0,400}定义字符串的最大允许大小。例如:

QRegExp regexp("^\s*([^\s]\s*){0,400}$");
QRegExpValidator *validator = new QRegExpValidator(regexp, this);
lineEdit->setValidator(validator);

最后一个,尽量避免它,只需处理textChanged信号并手动限制字符串。

相关问题