我注意到PyQt图形用户界面中QLabel()
的字体大小不太一致。让我们看看下面的例子。我已经为快速测试编写了一个完整的python文件。它将弹出一个带有两个标签的Qt窗口:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
import os
'''---------------------------------------------------------------------'''
''' '''
''' T E S T I N G '''
''' '''
'''---------------------------------------------------------------------'''
class TestWindow(QMainWindow):
def __init__(self):
super(TestWindow, self).__init__()
# 1. Set basic geometry and color.
# --------------------------------
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('Hello World')
palette = QPalette()
palette.setColor(QPalette.Window, QColor(200,200,200))
self.setPalette(palette)
self.show()
# 2. Create the central frame.
# ----------------------------
self.centralFrame = QFrame(self)
self.centralFrame.setFrameShape(QFrame.NoFrame)
self.centralLayout = QVBoxLayout()
self.centralFrame.setLayout(self.centralLayout)
self.centralLayout.setSpacing(5)
self.centralLayout.setContentsMargins(20,20,20,20)
self.setCentralWidget(self.centralFrame)
# 3. Do the test.
# ----------------
# TEST CASE 1
# The label with html
self.infoLbl = QLabel()
self.infoLbl.setTextFormat(Qt.RichText)
self.infoLbl.setFrameShape(QFrame.StyledPanel)
self.infoTxt = \
'<html> \
<head> \
</head> \
<body> \
<font size="10"> \
<p style="margin-left:8px;">My html text, font = 10pt</p> \
</font> \
</body> \
</html> '
self.infoLbl.setText(self.infoTxt)
self.infoLbl.setMaximumHeight(50)
self.infoLbl.setMaximumWidth(500)
# TEST CASE 2
# The label with a normal string
self.normalLbl = QLabel()
self.normalLbl.setFrameShape(QFrame.StyledPanel)
self.normalLbl.setText('My normal text, font = 10pt')
font = QFont()
font.setFamily("Arial")
font.setPointSize(10)
self.normalLbl.setFont(font)
self.normalLbl.setMaximumHeight(50)
self.normalLbl.setMaximumWidth(500)
# 4. Add both labels to the central layout.
# ------------------------------------------
self.centralLayout.addWidget(self.infoLbl) # <- The label with html snippet
self.centralLayout.addWidget(self.normalLbl) # <- The normal label
self.centralLayout.addWidget(QLabel()) # <- Just a spacer
if __name__== '__main__':
app = QApplication(sys.argv)
QApplication.setStyle(QStyleFactory.create('Fusion'))
testWindow = TestWindow()
app.exec_()
app = None
如果运行此代码,则会得到:
为什么两个标签的字体大小不相等?在
为了完整起见,这是我的系统:
我想我找到了答案。在
将html代码段替换为:
显然,html标记
<font size="10">
不能正常工作。但将其作为CSS样式属性插入,如style="font-size:10pt"
确实有效。不过,html标记应该可以正常工作。这闻起来像个Qt虫?在编辑: 显然这不是Qt缺陷。请参阅@ekhurvo的答案以获得澄清。在
在Qt4和Qt5中,
font
标记仍然完全受支持。因为Qt只支持a limited subset of HTML4,所以它已经被当前的HTML标准淘汰了。在这个例子的真正问题是由于对
size
属性的误解。这不指定点大小。相反,它指定(a)1-7范围内的固定值,或(b)相对于basefont
大小的正负值。因此,它所能做的就是使字体“变小”或“变大”,而准确的结果将完全取决于渲染引擎。在要设置精确的点大小,请使用css
font-size
属性:注意:请参阅CSS Properties Table,以获取Qt的富文本引擎支持的所有css属性的列表。在
正如你已经发现的,你似乎需要用风格来代替。更多信息请点击此处:
上面写着:
以及
相关问题 更多 >
编程相关推荐