As the title says. Solved. The solution is at the bottom of the article.
The background color of the Widget created from the QWidget subclass could not be set. However, when I tried the same with the inheritance source QWidget (), it worked for some reason.
What is this!
I looked it up, so I'll summarize it.
# coding: utf-8
from PySide2 import QtWidgets, QtGui, QtCore
class Widget(QtWidgets.QWidget):
def __init__(self):
super(Widget, self).__init__()
self.setStyleSheet("background-color:red")
layout = QtWidgets.QVBoxLayout()
button_widget = QtWidgets.QPushButton()
button_widget.setText("Inherited widget")
layout.addWidget(button_widget)
self.setLayout(layout)
def generate_widget():
parent_widget = QtWidgets.QWidget()
parent_widget.setStyleSheet("background-color:red;")
layout = QtWidgets.QVBoxLayout()
button_widget = QtWidgets.QPushButton()
button_widget.setText("QWidget")
layout.addWidget(button_widget)
parent_widget.setLayout(layout)
return parent_widget
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
hbox = QtWidgets.QHBoxLayout()
widget = Widget()
widget2 = generate_widget()
hbox.addWidget(widget)
hbox.addWidget(widget2)
self.setLayout(hbox)
def main():
app = QtWidgets.QApplication()
window = Window()
window.show()
exit(app.exec_())
if __name__ == "__main__":
main()
Like this, the background color works only on the background of the button.
The Qt Style Sheets Reference says: (Super translation)
QWidget
Only background, background-clip, and background-origin are supported.
** When subclassing from QWidget, you need to provide paintEvent as below. ** **
def paintEvent(self, event): opt = QtWidgets.QStyleOption() opt.init(self) painter = QtGui.QPainter(self) style = self.style() style.drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, painter, self)
So, if you put the above code in a subclass, it will be solved.
You did it!
![qWidget_bgcolor_test_02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/294868/05de106f-8322-b4d3-c8aa-c4794ce7a75c.png)
Recommended Posts