5

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.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Nerdrigo
  • 308
  • 1
  • 5
  • 14

2 Answers2

8

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.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
  • 3
    The extra eight pixels are coming from the `2*d->horizontalMargin` and the frame. The mysterious `horizontalMargin` and `verticalMargin` values are static constants found in [qlineedit_p.cpp](https://code.qt.io/cgit/qt/qt.git/tree/src/gui/widgets/qlineedit_p.cpp#n57), and are set to `2` and `1` respectively. The frame values are calculated by the style. So we have `2 * 2` (*horizonal margin*) plus `2 * 2` (*frame*) equals eight. With the exception of the constants, I was able to port all of the `sizeHint` code to pyside and verify the calculation. – ekhumoro Nov 15 '17 at 18:00
7

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

#setFixedWidth(int w)
MyLineEdit.setFixedWidth(120)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
samubreizhizel
  • 222
  • 2
  • 9
  • Do you know how I can use this in combination with " layout.addWidget(QLineEdit(), 0, 0) " ? – Ben Oct 06 '22 at 08:45