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() |
我最终使用
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() |