問題描述
我的代碼生成一個包含兩個 QWidget 的窗口,一個紅色 (wg1
) 和一個藍色 (wg2
).如果它們變成繼承自 QWidget 的 Fields(注釋掉),它們的顏色就會消失.
My code generates a Window containing two QWidgets, a red (wg1
) and a blue (wg2
) one. If they become Fields (commented out) which inherits from QWidget, their color disappears.
我的問題是:為什么 Field
(繼承自 QWidget
)需要有一行
My question is: Why is it necessary for a Field
(which inherits from QWidget
), to have the line
self.setAttribute(Qt.WA_StyledBackground, True)
在它的 __init__
方法中,而 QWidget 不需要這一行?
in its __init__
-method while a QWidget doesn't need this line?
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout
from PyQt5.QtCore import Qt
class Field(QWidget):
def __init__(self, name):
super().__init__()
self.name = name
# self.setAttribute(Qt.WA_StyledBackground, True)# !!!
def mousePressEvent(self, event):
print(f" click makes {self.name} green")
self.setStyleSheet("background: #00ff00;")
if __name__ == "__main__":
app = QApplication(sys.argv)
root = QWidget()
grid = QGridLayout()
root.setLayout(grid)
root.resize(300,100)
wg1 = QWidget()
wg2 = QWidget()
# wg1 = Field('wg1')
# wg2 = Field('wg2')
wg1.setStyleSheet("background: #aa1111;")
grid.addWidget(wg1, 0, 0)
wg2.setStyleSheet("background: #1111aa;")
grid.addWidget(wg2, 0, 2)
root.show()
sys.exit(app.exec_())
推薦答案
解釋在樣式表參考中與 QWidget 相關的部分:
如果您從 QWidget 繼承,您需要為您的自定義 QWidget 提供一個paintEvent,如下所示:
If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:
默認情況下,QWidget 會默認執行此操作,但 QWidget 子類不會,因此您要么設置標志,要么實現paintEvent.
By default, QWidget does that by default, but QWidget subclasses do not, so you either set the flag or you implement the paintEvent.
無論如何,請考慮使用 樣式表選擇器 并避免通用/通用語法,因為它們通常會導致復雜的子小部件出現意外行為.
In any case, consider using stylesheet selectors and avoid generic/universal syntax as they often result in unexpected behavior for complex child widgets.
這篇關于PyQt5:樣式表和來自 QWidget 的繼承的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!