I created some QLineEdit
, which have different sizes.
I want to set the max length of those to suit the width of them.
To be more specific: for example, with a width of 50, I will only allow to enter about 7 characters, because the size of each character is different.
How can I exactly calculate the maximum length needed?
You can set a limit based on the width of myLineEdit
such that it will be able to fit all characters up to that limit by doing this:
#include <QFontMetrics>
#include <QLineEdit>
QLineEdit myLineEdit;
// get max character width of the line edit's font
int maxWidth = QFontMetrics(myLineEdit->font()).maxWidth();
// find the character limit based on the max width
int charlimit = myLineEdit.width() / maxWidth;
// set the character limit on the line edit
myLineEdit->setMaxLength(charlimit);
However, here are some reasons you probably don't want to in production code: