为什么这个自定义QWidget没有正确显示

时间:2018-05-01 18:32:38

标签: python-3.x background pyqt5 qwidget qtstylesheets

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

以下代码,以其当前形式,将在窗口中显示绿色阴影QWidget,这正是我想要的。但是,在评论该行时:

self.widget = QWidget(self.centralwidget)

并取消注释,

self.widget = Widget_1(self.centralwidget)

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

我不打算使用任何类型的自动布局,原因我不需要进入这里。你能帮助我理解绿色矩形没有显示的原因,以及为了利用Widget_1类需要做些什么修正?

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

1 个答案:

答案 0 :(得分:1)

遵循这篇Qt Wiki文章:

您必须在自定义paintEvent子类中实现QWidget才能使用样式表。此外,由于窗口小部件不是布局的一部分,因此必须为其指定父窗口,否则将不会显示它。所以你的Widget_1类必须如下所示:

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)