python - 在 PyQt5 中,如何将样式表 _only_ 应用于自定义 QWidget 子类?
问题描述
有一些相关的问题,例如
- 自定义 Qt 类的 CSS 选择器(虽然不是 Python 特定的)
- 如何阻止子小部件继承父样式表并使用系统默认值?(不是 Python 特定的,也不是自定义子类)
然而,他们都没有解决我的问题。
基本上我的情况如下:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QLabel
from PyQt5.QtCore import QCoreApplication, Qt
class MyCustomWidget(QWidget):
"""I want to draw a border around instances of this class (but not its children)."""
def __init__(self):
super().__init__()
layout = QHBoxLayout()
layout.addWidget(QLabel('foo'))
layout.addWidget(QLabel('bar'))
self.setLayout(layout)
# I want to draw a border around all instances of `MyCustomWidget`.
# The following only applies the style sheet its children.
self.setStyleSheet('border: 1px solid black;')
# The following doesn't apply the style sheet to any object.
self.setStyleSheet('.MyCustomWidget { border: 1px solid black; }')
# The following doesn't apply the style sheet to any object.
self.setObjectName('custom')
self.setStyleSheet('#custom { border: 1px solid black; }')
class MainWidget(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
layout.addWidget(QLabel('Title'))
layout.addWidget(MyCustomWidget())
self.setLayout(layout)
if __name__ == '__main__':
QCoreApplication.setAttribute(Qt.AA_X11InitThreads)
app = QApplication(sys.argv)
main_window = QMainWindow()
main_window.setCentralWidget(MainWidget())
main_window.show()
app.exec_()
在最终的应用程序中,我希望只在MyCustomWidget
(即不是它的孩子)的实例周围绘制一个边框。但是,以下尝试均未成功:
self.setStyleSheet('border: 1px solid black;')
-- 这仅将样式表应用于子项。self.setStyleSheet('.MyCustomWidget { border: 1px solid black; }')
- 这是我希望的解决方案,但它没有将样式表应用于任何对象(这个答案提到类名只存在于必须指定的命名空间内,但我找不到它,因为className
PyQt5 中似乎不存在该方法)。self.setObjectName('custom'); self.setStyleSheet('#custom { border: 1px solid black; }')
- 从文档来看,这应该也可以,但由于某种原因它没有。此外,为实例拟定人造对象名称也很不方便,MyCustomWidget
仅对每个实例应用相同的样式表。这正是类选择器的用途。
有谁知道如何解决这个问题,最好是在样式表中使用类选择器?
$ python -m pip freeze | grep PyQt5
PyQt5==5.15.4
PyQt5-Qt5==5.15.2
PyQt5-sip==12.9.0
$ python --version
Python 3.9.5
解决方案
推荐阅读
- google-cloud-dataflow - 谷歌数据流管道卡在 GroupByKey
- macros - 如何使用SPSS查找所有变量的最大值和最小值并在表格中显示?
- gradle - 从 Eclipse 启动 Web 应用程序的问题以及如何在 build.gradle 中将码头升级到 9.4.20
- java - 如何使用哈希图添加增量值
- sapui5 - 和过滤 SAP UI5
- java - 有没有办法格式化您的输出,使其输出更均匀?
- java - 如何为 tableview 使用多个泛型类型?
- c# - 组合框的过滤 - 奇怪的行为
- android - 在列表视图底部添加视图
- .net - 如何在.Net Core 3 ASP.NET MVC 中不使用第三方记录器登录到文件?