我希望文本自动适应标签内部。 随着QLabel的宽度变得越来越窄,文本格式占据多行。基本上我正在寻找一种格式化方法,就像我们调整Web浏览器窗口大小时格式化html文本一样。
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()
答案 0 :(得分:0)
我最终使用resizeEvent()
的{{1}}来获取实时标签的宽度值,该值用于格式化标签上的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()