【发布时间】:2023-03-20 04:26:01
【问题描述】:
填充属性未按预期工作。
这是我的代码:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel
class Window(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(450, 450)
tracking_description = QLabel()
tracking_description.setStyleSheet('''
border: 2px solid;
border-radius: 8px;
padding-top: 0px;
padding-bottom: 0px;
padding-right: 10px;
padding-left: 10px;
''')
tracking_description.setText("Consente di scegliere una \
delle camere installate sul territorio e impostarla \
in <b>modalità tracciante</b>.<br />Durante questa fase \
il sistema osserverà i veicoli che transitano nella scena \
e <b>definirà in maniera automatica delle aree di \
parcheggio</b>.<br />\Propedeuticamente, sarà possibile \
definire le scene di osservazione che una specifica camerà \
dovrà gestire.")
tracking_description.setWordWrap(True)
tracking_description.setFixedWidth(408)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addWidget(tracking_description)
vbox.addStretch(1)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addLayout(vbox)
hbox.addStretch(1)
self.setLayout(hbox)
if __name__ == "__main__":
app = QApplication(["TODO"])
win = Window()
win.show()
sys.exit(app.exec_())
如果我将 tracking_description QLabel 的 padding-right 和 padding-left 保持为 10px,这就是输出(也有意外的顶部和底部填充):
如果我将padding-right 和padding-left 设置为30px,这就是输出(预期的顶部和底部填充为0px):
为什么会有这种行为?
【问题讨论】:
-
嗯,这似乎是一个复合问题,可能与字体度量和固定宽度的要求有关。 QLabel 根据可用空间调整其大小,考虑多种因素,包括填充、间距、大小约束等,这通常是“概率猜测”,有时容易出现小错误。如果仔细观察,两个框的高度相同,计算为 10 行文本。我怀疑是否有直接的解决方案,唯一可能的答案是使用 QTextDocument ,然后根据填充和内容设置最大高度。
-
好的,我会尝试使用 QTextDocument!非常感谢。
-
我无法重现该行为。但可能有助于设置“qproperty-indent:0;”在样式表中。如果此属性为负数或未设置,Qt 会自动添加缩进。
-
天哪!!!! @bzs "qproperty-indent:0;"解决这个问题!!!!你真是个天才!谢谢
标签: python pyqt5 qtstylesheets