C++ QLineEdit: setmaxlength() for number of bytes and not the number of the characters?

StackOverflow https://stackoverflow.com/questions/15613805

  •  29-03-2022
  •  | 
  •  

Question

I have a QLineEdit in my application in which I should be able to enter a maximum of 10byte characters in english and while entering Japanese characters , if the character is of 2byte , I should be able to enter only 5 characters in japanese and if the Japanese character is a 1byte character, I should be able to enter 10 characters in japanese. Please help me with this.

I tried using

QLineEdit::setMaxLength(10) 

but it is working fine only with English characters but not with Japanese characters.

Any idea/suggestions ???

Was it helpful?

Solution 2

I resolved my issue as follow :

In LineEdit Slot:

 void ABC::on_abc_cmd_task_tableWidget_linedit_cellChanged(QString str)
 {
    QLineEdit *edit = qobject_cast<QLineEdit *>(sender());

    if(edit)
    {
        QByteArray chkDataSize;
        chkDataSize.clear();
        chkDataSize.append(str);
        int dSize = chkDataSize.size();

        qDebug() << "total Bytes in text = " << dSize;
        qDebug() << "Max length before = " << edit->maxLength();

        if (dSize == edit->maxLength())
        {
             edit->setMaxLength(str.size());
        }

        qDebug() << "Max length after = " << edit->maxLength();

      }


 }

Well tested with Russian Characters / Japanese Character etc.

OTHER TIPS

Note that the number of bytes used for a character is entirely dependent on which encoding you use to store it in. QString uses 2 bytes for all characters, but presumably you are interested in a particular encoding such as UTF-8. I would suggest that rather than using setMaxLength you need to create a QValidator subclass which implements your particular validation rules and set it on your line edit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top