【问题标题】:How to auto-format the QLabel text如何自动格式化 QLabel 文本
【发布时间】:2016-08-16 09:34:43
【问题描述】:

我希望文本自动适应标签内。 随着 QLabel 的宽度越来越窄,文本格式会占据多行。本质上,我正在寻找一种方法来格式化它,就像我们调整网络浏览器窗口大小时格式化 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()

【问题讨论】:

  • 你试过 label.setWordWrap(True) 吗?

标签: python qt pyqt qlabel


【解决方案1】:

我最终使用QLabelresizeEvent() 来获取实时标签的宽度值,该值用于即时格式化标签的单字体文本:

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()

【讨论】:

  • Frank Osterfeld 的建议有什么问题?我很确定 wordWrap 属性会为你做到这一点。
  • Fran 的建议很棒!我错过了他的评论。我希望我能早点看到它!谢谢!
猜你喜欢
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多