How can I limit text box width of QLineEdit to display at most four characters?
Solution 1
If what you want is modify your QLineEdit
width and fix it, use:
#setFixedWidth(int w)
MyLineEdit.setFixedWidth(120)
Solution 2
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.
Nerdrigo
Words to live by: "Do or do not, there is no try" "We must know, we will know"
Updated on July 14, 2022Comments
-
Nerdrigo almost 2 years
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.
-
ekhumoro over 6 yearsThe extra eight pixels are coming from the
2*d->horizontalMargin
and the frame. The mysterioushorizontalMargin
andverticalMargin
values are static constants found in qlineedit_p.cpp, and are set to2
and1
respectively. The frame values are calculated by the style. So we have2 * 2
(horizonal margin) plus2 * 2
(frame) equals eight. With the exception of the constants, I was able to port all of thesizeHint
code to pyside and verify the calculation.