如何自动格式化QLabel文本
问题描述:
我希望文本自动适应标签内部。 随着QLabel的宽度变得更窄,文本格式占据多行。基本上,我正在寻找一种方法来格式化它,就像在调整Web浏览器窗口大小时格式化HTML文本一样。如何自动格式化QLabel文本
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()
答
我已经结束了使用QLabel
的resizeEvent()
得到它用于标签的monofont文本格式上飞实时标签的宽度值:
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('\n')[-1])<width*0.1:
new = new + ' ' + word
else:
new = new + '\n' + ' ' + 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()
+0
_Frank Osterfeld_建议有什么问题?我很确定wordWrap属性会为你做到这一点。 – ymoreau
+0
Fran的建议非常棒!我错过了他的评论。我希望我能早日看到它!谢谢! – alphanumeric
有你试过label.setWordWrap(True)? –