我正在用一个更好的代码示例重试这个问题。
下面的代码,以其当前形式,将在窗口中显示一个绿色阴影QWidget
,这就是我想要的。 但是,当注释掉该行时:
self.widget = QWidget(self.centralwidget)
和取消评论,
self.widget = Widget_1(self.centralwidget)
绿色框不显示。 Widget_1
类是QWidget
的简单子类,所以我试图绕开故障发生的位置。 没有错误消息,并且Widget_1
类中的print("Test")
行输出得很好,所以我知道一切都被正确调用。
我不打算使用任何类型的自动布局,原因我不需要在这里讨论。 您能帮助我理解为什么绿色矩形没有显示,以及我需要进行哪些更正才能使用 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
附和这篇Qt Wiki文章:
- 如何更改QWidget的背景颜色
必须在自定义QWidget
子类中实现paintEvent
才能使用样式表。此外,由于小部件不是布局的一部分,因此您必须为其指定父级,否则将不会显示。因此,您的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)