PyQt:通过样式表的属性仅用于绘画?

PyQt: properties via stylesheet only for painting?

我想在 PyQt5 中使用 style sheet 来布局自定义小部件。通常这是可行的:小部件显示有修改后的属性。然而,小部件的 属性(例如 style-sheet font-familyQLabel.label())似乎保持默认值(例如下面的最小示例)。

样式sheet是否只用于绘制小部件而不改变小部件本身? 有没有办法获得 'new' 属性?否则无法使用例如 FontMetricsstyle sheet 的组合?

import sys

from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtGui import QFontInfo

stylesheet = '''
QLabel{
    font-family: Wingdings;
}
'''

app = QApplication(sys.argv)
label = QLabel('Hello World!')
label.setStyleSheet(stylesheet)
print(QFontInfo(label.font()).family())  # prints out: MS Shell Dlg 2; expected: Wingdings
label.show()
app.exec()

您的怀疑确实是正确的:在使用样式表时,许多小部件属性被忽略,两者 用于它们的 getter 和 setter。

没有直接的方法知道这些值,因为它们都由 Qt 的解析器在内部管理。

最重要的是,palette()font()(显然 fontMetrics())不受影响,因此您无法知道用于样式表,如果您尝试设置字体或设置新的调色板,您将得不到任何结果(所有这一切都假设您实际上是在样式表中设置一些颜色或字体,很明显)。

这也适用于其他小部件特定属性(例如,QFrame 边框样式),甚至可能在不同 styles/systems.

上的结果略有不同

这也是您应该使用样式表或 QPalette 的原因,因为混合使用它们可能会导致意外行为。

来自 QWidget.palette() 文档:

Warning: Do not use this function in conjunction with Qt Style Sheets.

来自 QWidget.font() 文档:

Note : If Qt Style Sheets are used on the same widget as setFont(), style sheets will take precedence if the settings conflict.