PyQt5 QGraphicsSiteMgroup中的子项事件

2024-10-04 03:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图形项目组-3个矩形和文本

我想使文本可编辑,但不能。焦点设置在文本上,但仍然无法编辑。试图将父组设置为停止处理子事件,但无效

class Uml(QGraphicsItemGroup):
def __init__(self, x, y, scene):
    super().__init__()
    self.setFiltersChildEvents(False)

    self.headerR = QGraphicsRectItem(x,y,70,30)
    self.header = QGraphicsTextItem("header")
    self.header.setPos(x,y)
    self.header.setTextInteractionFlags(Qt.TextEditorInteraction)

    self.attrR = QGraphicsRectItem(x, y+30,70,50)
    self.attr = QGraphicsTextItem("attributes")   
    self.attr.setPos(x,y+30)

    self.methodsR = QGraphicsRectItem(x, y+80,70,50)
    self.methods = QGraphicsTextItem("methods")   
    self.methods.setPos(x,y+80)
    
    self.addToGroup(self.headerR)
    self.addToGroup(self.header)
    self.addToGroup(self.attrR)
    self.addToGroup(self.attr)
    self.addToGroup(self.methodsR)
    self.addToGroup(self.methods)

    scene.addItem(self)
    self.setFlag(QGraphicsItem.ItemIsMovable, True)

Tags: 文本self编辑initsceneheadermethodsattr
1条回答
网友
1楼 · 发布于 2024-10-04 03:29:31

几乎每次我尝试使用QGraphicsGroupItem时,我都会放弃它,因为他们的行为(特别是与输入事件相关时)往往不可靠,根据我的研究,我不是唯一一个面临这些问题的人

如果您只需要按照一个共同的祖先对所有项进行“分组”,那么创建QGraphicsItem的子类并将项创建为其子类就更加容易和可靠,这可以通过添加父类作为构造函数的参数或使用setParentItem()来实现。然后,由于抽象QGraphicsItem需要同时实现boundingRect()paint(),因此第一个只需返回childrenBoundingRect(),第二个只需返回pass

在下面的代码重写中,我冒昧地将“标签”重新复制到它们所指的矩形上,这更有意义。
此外,除非您确实需要,否则通常最好避免在基本形状项(如QGraphicsRectItem、QGraphicsSellipseitem等)中设置相对位置,因为这会使坐标引用比实际更复杂:请记住,项目总是在坐标(0, 0)处创建的,并且当您使用(x, y, width, height),{}和{}指的是项目的矩形不是项目的位置,在手动更改之前仍然是(0, 0)

class Uml(QGraphicsItem):
    def __init__(self, x, y, scene):
        super().__init__()

        self.headerR = QGraphicsRectItem(0, 0, 70, 30, self)
        self.header = QGraphicsTextItem("header", self.headerR)
        self.header.setTextInteractionFlags(Qt.TextEditorInteraction)

        self.attrR = QGraphicsRectItem(0, 0, 70, 50, self)
        self.attr = QGraphicsTextItem("attributes", self.attrR)
        self.attrR.setY(30)

        self.methodsR = QGraphicsRectItem(0, 0, 70, 50, self)
        self.methods = QGraphicsTextItem("methods", self.methodsR)
        self.methodsR.setY(80)

        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        scene.addItem(self)
        self.setPos(x, y)

    def boundingRect(self):
        return self.childrenBoundingRect()

    def paint(self, *args):
        pass

相关问题 更多 >