Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit text box width of QLineEdit to display at most four characters?

I am working with a GUI based on PySide. I made a (one line) text box with QLineEdit and the input is just four characters long, a restriction I already successfully applied.

The problem is I have a wider than needed text box (i.e. there is a lot of unused space after the text). How can I shorten the length of the text box?

I know this is something that is easily fixed by designing the text box with Designer; however, this particular text box is not created in Designer.

like image 268
Nerdrigo Avatar asked Dec 08 '22 16:12

Nerdrigo


2 Answers

If what you want is modify your QLineEdit width and fix it, use:

#setFixedWidth(int w)
MyLineEdit.setFixedWidth(120)
like image 181
SRD Avatar answered Jan 16 '23 18:01

SRD


Looking at the source of QLineEdit.sizeHint() one sees that a line edit is typically wide enough to display 17 latin "x" characters. I tried to replicate this in Python and change it to display 4 characters but I failed in getting the style dependent margins of the line edit correctly due to limitations of the Python binding of Qt.

A simple:

e = QtGui.QLineEdit()
fm = e.fontMetrics()
m = e.textMargins()
c = e.contentsMargins()
w = 4*fm.width('x')+m.left()+m.right()+c.left()+c.right()

is returning 24 in my case which however is not enough to display four characters like "abcd" in a QLineEdit. A better value would be about 32 which you can set for example like.

e.setMaximumWidth(w+8) # mysterious additional factor required 

which might still be okay even if the font is changed on many systems.

like image 40
Trilarion Avatar answered Jan 16 '23 18:01

Trilarion