简体   繁体   中英

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 (ie 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.

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

#setFixedWidth(int w)
MyLineEdit.setFixedWidth(120)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM