如何在Qt Widget中格式化文本

2 投票
1 回答
5324 浏览
提问于 2025-04-18 15:43

下面的代码创建了一个简单的窗口,里面有一个 QLabeltextDict 被格式化成一个字符串变量 info,看起来很不错。但是,一旦把这个文本赋值给 QLabel(或者其他的 QWidget),这些漂亮的格式就全都没了。

问题:怎么才能保持文本的格式呢?

这里有一张截图,展示了文本在一个控件上的样子,以及通过 print() 输出的结果。

enter image description here

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

textDict={'Python': 'Is a widely used general-purpose, high-level programming language', 'Its_design': 'philosophy emphasizes code readability, and its syntax', 'allows': 'programmers to express concepts in fewer lines of code than would be possible in languages such as C'}

label=QtGui.QLabel()
info=''
for key in textDict: info+=(key+str(textDict[key]).rjust(150-len(key),'.'))+'\n'    
label.setText(info)
label.show()
sys.exit(app.exec_())

请注意,文本应该是右对齐的,但在 Qt 的 QLabel 中完全没有这个效果。

编辑:

最后在Gerrat的巨大帮助下(谢谢!):要实现这个效果,应该使用等宽字体。我测试了两种字体,效果都不错:font-family: Lucida Consolefont-family: Courier New

语法如下:

label=QtGui.QLabel()

label.setStyleSheet(" font-size: 10px; qproperty-alignment: AlignJustify; font-family: Courier New;")

enter image description here

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

textDict={'Python': 'Is a widely used general-purpose, high-level programming language', 'Its_design': 'philosophy emphasizes code readability, and its syntax', 'allows': 'programmers to express concepts in fewer lines of code than would be possible in languages such as C'}
class AppWindow(QtGui.QMainWindow):
    def __init__(self):
        super(AppWindow, self).__init__()
        mainWidget=QtGui.QWidget()
        self.setCentralWidget(mainWidget)
        mainLayout = QtGui.QVBoxLayout()
        mainWidget.setLayout(mainLayout)   
        for key in textDict:
            info=(key+str(textDict[key]).rjust(150-len(key),'.'))+'\n'  
            label=QtGui.QLabel()
            label.setText(info)
            label.setStyleSheet(" font-size: 10px; qproperty-alignment: AlignJustify; font-family: Courier New;")
            mainLayout.addWidget(label)

window=AppWindow()
window.show()
sys.exit(app.exec_())

1 个回答

2

你可以使用一部分HTML来给内容添加样式。想要实现你想要的效果,有一个方法就是用 <br> 来换行,而不是用 '\n'

补充: 出现问题的一个原因是没有使用等宽字体。你的点(比如“.”)占用的空间和普通字符不一样。你尝试的“每个文本编辑器”都是在用等宽字体……如果你在某个编辑器里选择一个比例字体,就会看到内容变得混乱。总的来说,除了使用HTML,你可以选择一种固定宽度的字体。

撰写回答