pyqt“ ItemIgnoresParentOpacity”标志被忽略

问题描述

我已经花了一些时间来制作我的问题的最小可复制示例。

使用PyQt5,我有一个经典的主窗口,其中的QGraphicsView链接到QGraphicsScene。

在现场,我有一个NodeHover项(绿色圆圈)和一个TreeNode子级(正方形)。 认情况下,NodeHover项是透明的,并且在悬浮时会变为不透明。

enter image description here

无论父项的不透明度如何,我都希望其子项(TreeNode)始终保持不透明状态。我已经尝试在两个项目中都设置标志,如下所示,但是它们似乎不起作用。

import sys
from PyQt5.QtWidgets import QGraphicsScene,QGraphicsView,QMainWindow,QApplication,qtoolbar,QStatusBar,QAction,QGraphicsItem,QGraphicslineItem,QLabel,QGraphicsEllipseItem,qgraphicstextitem

from PyQt5.QtCore import *
from PyQt5.QtGui import QPainter,QIcon,QPen,QBrush,QTransform


class NodeHover(QGraphicsItem):
    def __init__(self,*args,**kwargs):
        super(NodeHover,self).__init__(*args,**kwargs)
        self.setopacity(0.1)
        self.setAcceptHoverEvents(True)
        # Setting the flag so Item doesn't propagate its opacity to children
        self.GraphicsItemFlag(QGraphicsItem.ItemDoesntPropagateOpacitytochildren)

    def hoverEnterEvent(self,event):
        self.setopacity(1) # When mouse enters item,make it opaque
    def hoverLeaveEvent(self,event):
        self.setopacity(0.1) # When mouse leaves item,make it transparent

    def boundingRect(self):
        return QRectF(0,20,20)

    def paint(self,painter,option,widget):
        painter.setBrush(QBrush(Qt.green))
        painter.drawEllipse(QPointF(10,10),10,10)

    
class TreeNode(QGraphicsItem):
    def __init__(self,**kwargs):
        super(TreeNode,**kwargs)
        # Setting the flag to ignore parent's opacity
        self.GraphicsItemFlag(QGraphicsItem.ItemIgnoresParentOpacity)

    def boundingRect(self):
        return QRectF(100,100,100)

    def paint(self,widget):
        painter.drawRect(110,110,80,80)


class GView(QGraphicsView):
    def __init__(self,parent,**kwargs):
        super().__init__(*args,**kwargs)
        self.parent = parent
        self.setGeometry(100,700,450)
        self.show()


class Scene(QGraphicsScene):
    def __init__(self,parent):
        super().__init__(parent)
        self.parent = parent
        hoverItem = NodeHover() # create a NodeHover item
        self.addItem(hoverItem)
        nodeItem = TreeNode()   # create a TreeNode item and make it hoverItem's child
        nodeItem.setParentItem(hoverItem)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(900,70,1000,800)
        self.createGraphicView()
        self.show()

    def createGraphicView(self):
        self.scene = Scene(self)
        gView = GView(self)
        scene = Scene(gView)
        gView.setScene(scene)
        # Set the main window's central widget
        self.setCentralWidget(gView)

# Run program
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

解决方法

要为QGraphicsItem设置标志,必须使用setFlag()方法:

self.setFlag(QGraphicsItem.ItemDoesntPropagateOpacityToChildren)
self.setFlag(QGraphicsItem.ItemIgnoresParentOpacity)

注意:这些标志之一就足够了。