下面的代码使用 QLabel 创建了一个简单的窗口。 textDict 被很好地格式化为字符串变量 info。但是一旦将文本分配给 QLabel(或任何其他 QWidget),这种漂亮的格式就会全部丢失。
问题:如何保留文本格式。
这是显示小部件上的文本以及 print()
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 的大力帮助下(谢谢!): 应该使用 Monospace 字体来实现这个技巧。我已经用 twos 进行了测试并且它有效: font-family:Lucida Console 和 font-family:Courier New 语法:
label=QtGui.QLabel()
label.setStyleSheet("font-size: 10px; qproperty-alignment: AlignJustify; font-family: Courier New;")
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_())
请您参考如下方法:
您应该能够使用 subset of HTML给它设计风格。完成你想要的事情的一种方法是,而不是 '\n' , 你可以使用 <br>换行符。
编辑: 它搞砸的原因之一是它没有使用等宽字体。你的点没有使用与常规字符相同的空间。您正在尝试的“每个文本编辑器”都在使用等宽字体……为您的一位编辑器选择一种比例字体,然后看它搞砸了。要点是,您可以选择固定宽度的字体,而不是使用 HTML。
