为什么这个自定义 QWidget 不能正确显示

Why doesn't this custom QWidget display correctly

我正在用一个更好的代码示例重试这个问题。

下面的代码在其当前形式中将在 window 中显示绿色阴影 QWidget,这正是我想要的。但是,在注释掉该行时:

self.widget = QWidget(self.centralwidget)

并取消注释,

self.widget = Widget_1(self.centralwidget)

绿框不显示。 Widget_1 class 是 QWidget 的一个简单的子 class,所以我想弄清发生故障的地方。没有错误消息,Widget_1 class 中的 print("Test") 行输出正常,所以我知道一切都被正确调用。

我不打算使用任何类型的自动布局,原因我不需要在这里详述。你能帮我理解为什么没有显示绿色矩形,以及我需要进行哪些更正才能使用 Widget_1 class?

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtCore import QRect
import sys

class Main_Window(object):
    def setupUi(self, seating_main_window):
        seating_main_window.setObjectName("seating_main_window")
        seating_main_window.setEnabled(True)
        seating_main_window.resize(400, 400)

        self.centralwidget = QWidget(seating_main_window)
        self.centralwidget.setObjectName("centralwidget")

        ###########  The following two lines of code are causing the confusion  #######

        #  The following line, when uncommented, creates a shaded green box in a window
        self.widget = QWidget(self.centralwidget)  # Working line

        #  The next line does NOT create the same shaded green box.  Where is it breaking?
        # self.widget = Widget_1(self.centralwidget) # Non-working line

        self.widget.setGeometry(QRect(15, 150, 60, 75))
        self.widget.setAutoFillBackground(False)
        self.widget.setStyleSheet("background: rgb(170, 255, 0)")
        self.widget.setObjectName("Widget1")

        seating_main_window.setCentralWidget(self.centralwidget)

class Widget_1(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        self.setMinimumSize(10, 30)  # I put this in thinking maybe I just couldn't see it
        print("Test")   # I see this output when run when Widget_1 is used above

class DemoApp(QMainWindow, Main_Window):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

if __name__ == '__main__':  # if we're running file directly and not importing it
    app = QApplication(sys.argv)  # A new instance of QApplication
    form = DemoApp()  # We set the form to be our ExampleApp (design)
    form.show()  # Show the form
    app.exec_()  # run the main function

根据这篇 Qt Wiki 文章:

您必须在自定义 QWidget 子 class 中实施 paintEvent 才能使用样式表。另外,由于小部件不是布局的一部分,您必须给它一个父级,否则它不会显示。所以你的 Widget_1 class 必须是这样的:

from PyQt5.QtWidgets import QStyleOption, QStyle
from PyQt5.QtGui import QPainter

class Widget_1(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent) # set the parent
        print("Test")

    def paintEvent(self, event):
        option = QStyleOption()
        option.initFrom(self)
        painter = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, option, painter, self)
        super().paintEvent(event)