简体   繁体   English

如何限制QLineEdit的文本框宽度最多显示四个字符?

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

I am working with a GUI based on PySide. 我正在使用基于PySide的GUI。 I made a (one line) text box with QLineEdit and the input is just four characters long, a restriction I already successfully applied. 我使用QLineEdit制作了一个(一行)文本框,输入内容只有四个字符,这是我已经成功应用的限制。

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; 我知道可以通过使用Designer设计文本框来轻松解决此问题。 however, this particular text box is not created in Designer. 但是,此特定的文本框不是在Designer中创建的。

If what you want is modify your QLineEdit width and fix it, use: 如果您要修改QLineEdit宽度并修复它,请使用:

#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. 查看QLineEdit.sizeHint()源代码后 ,您会发现行编辑的宽度通常足以显示17个拉丁“ x”字符。 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. 我尝试在Python中复制此代码并将其更改为显示4个字符,但由于Qt的Python绑定的限制,我无法正确获取行的样式相关边距。

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. 在我的情况下返回24,但这不足以在QLineEdit中显示四个字符,例如“ abcd”。 A better value would be about 32 which you can set for example like. 更好的值大约是32,您可以设置例如。

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

which might still be okay even if the font is changed on many systems. 即使在许多系统上更改了字体,也可能仍然可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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