首页 > 解决方案 > 在 PyQt5 中,如何将样式表 _only_ 应用于自定义 QWidget 子类?

问题描述

有一些相关的问题,例如

然而,他们都没有解决我的问题。

基本上我的情况如下:

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(即不是它的孩子)的实例周围绘制一个边框。但是,以下尝试均未成功:

有谁知道如何解决这个问题,最好是在样式表中使用类选择器?


$ 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

标签: pythonpyqtpyqt5qtstylesheets

解决方案


推荐阅读