gpt4 book ai didi

python - 将 QGraphicsDropShadowEffect 与多个小部件一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:57 26 4
gpt4 key购买 nike

我想使用 QGraphicsDropShadowEffect 在几个小部件上设置阴影,我想知道是否有更好的方法可以做到这一点,而不必像在我的下面的例子。是否可以创建一个类或其他东西来调用,以便我只需要在小部件上设置 setGraphicsEffect() ?我已经尝试为它创建几个类,但我仍然只能让它们创建一个阴影。

import sys
from PyQt5.QtWidgets import QWidget, QHBoxLayout, \
QGraphicsDropShadowEffect, QPushButton, QApplication, QComboBox


class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
layout = QHBoxLayout()

self.shadow = QGraphicsDropShadowEffect()
self.shadow.setBlurRadius(5)
self.shadow.setXOffset(3)
self.shadow.setYOffset(3)

self.shadow2 = QGraphicsDropShadowEffect()
self.shadow2.setBlurRadius(5)
self.shadow2.setXOffset(3)
self.shadow2.setYOffset(3)

self.btn = QPushButton("Button")
self.btn.setGraphicsEffect(self.shadow)
self.combo = QComboBox()
self.combo.setGraphicsEffect(self.shadow2)

layout.addWidget(self.btn)
layout.addWidget(self.combo)
self.setLayout(layout)

if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()

最佳答案

docs声明相同的 QGraphicsEffect 不能被其他小部件共享:

If effect is the installed effect on a different widget, setGraphicsEffect() will remove the effect from the widget and install it on this widget.

所以你必须创建一个 QGraphicsEffect对于每个小部件,但如果您不想编写大量代码并希望应用具有相似特征的效果,您可以遍历这些小部件,为此您可以使用 findChildren(...) .

import sys
from PyQt5.QtWidgets import QWidget, QHBoxLayout, \
QGraphicsDropShadowEffect, QPushButton, QApplication, QComboBox


class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
layout = QHBoxLayout(self)

self.btn = QPushButton("Button")
self.combo = QComboBox()

layout.addWidget(self.btn)
layout.addWidget(self.combo)

for child in self.findChildren(QWidget):
shadow = QGraphicsDropShadowEffect(blurRadius=5, xOffset=3, yOffset=3)
child.setGraphicsEffect(shadow)

if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

关于python - 将 QGraphicsDropShadowEffect 与多个小部件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52066040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com