如何自动格式化 QLabel 文本
How to auto-format the QLabel text
我希望文本自动适合标签内部。
随着 QLabel 的宽度变得更窄,文本格式占据多行。本质上,我正在寻找一种格式化它的方法,就像我们调整网络浏览器 window.
大小时格式化 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()
我最终使用 QLabel
的 resizeEvent()
获取实时标签的宽度值,该值用于即时格式化标签的单字体文本:
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()
我希望文本自动适合标签内部。 随着 QLabel 的宽度变得更窄,文本格式占据多行。本质上,我正在寻找一种格式化它的方法,就像我们调整网络浏览器 window.
大小时格式化 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()
我最终使用 QLabel
的 resizeEvent()
获取实时标签的宽度值,该值用于即时格式化标签的单字体文本:
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()