How to auto-format the QLabel text
我希望文本自动适应标签内。
随着 QLabel 的宽度越来越窄,文本格式会占据多行。本质上,我正在寻找一种方法来格式化它,就像我们调整 Web 浏览器窗口大小时格式化 html 文本一样。
1 2 3 4 5 6
|
label =QtGui. QLabel()
text =“Somewhere over the rainbow Way up high And the dreams that you dreamed of Once in a lullaby”
label.setText(text)
label.show()
|
- 你试过 label.setWordWrap(True) 吗?
我最终使用 QLabel 的 resizeEvent() 来获取实时标签的宽度值,该值用于即时格式化标签的单字体文本:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
text =“Somewhere over the rainbow Way up high And the dreams that you dreamed of Once in a lullaby…”
class Label(QtGui.QLabel):
def __init__(self, parent=None):
super(Label, self).__init__(parent)
def resizeEvent(self, event):
self.formatText()
event.accept()
def formatText(self):
width = self.width()
text = self.text()
new = ”
for word in text.split():
if len(new.split(‘\
‘)[–1])<width*0.1:
new = new + ‘ ‘ + word
else:
new = new + ‘\
‘ + ‘ ‘ + word
self.setText(new)
myLabel = Label()
myLabel.setText(text)
myLabel.resize(300, 50)
font = QtGui.QFont(“Courier New”, 10)
font.setStyleHint(QtGui.QFont.TypeWriter)
myLabel.setFont(font)
myLabel.formatText()
myLabel.show()
|
- Frank Osterfeld 的建议有什么问题?我很确定 wordWrap 属性会为您做到这一点。
-
弗兰的建议很棒!我错过了他的评论。我希望我能早点看到它!谢谢!
来源:https://www.codenong.com/36799152/
微信公众号
手机浏览(小程序)
Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(): Failed to enable crypto in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_10490.jpg): failed to open stream: operation failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57