gpt4 book ai didi

python - QGraphicsItemGroup.removeFromGroup——子项目没有正确地重新定位到场景

转载 作者:行者123 更新时间:2023-11-28 21:56:20 26 4
gpt4 key购买 nike

我正在尝试从 QGraphicsItemGroup 中删除 QGraphicsItem。当调用 removeFromGroup 时,该项目被删除(当然)。但是,它在场景中不再可见。我必须调用 Scene.addItem(item) 才能使其再次出现。这显然是你不应该做的事情(我收到了这样做的警告)。但我似乎找不到另一种解决方法。

这是一个最小的例子:

import sys 

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class MainWindow(QMainWindow):

def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)

self.view = QGraphicsView()
self.scene = QGraphicsScene()
self.view.setScene(self.scene)

self.setCentralWidget(self.view)


def add_group(scene):
group = QGraphicsItemGroup()
text = QGraphicsTextItem()
text.setPlainText("I'm visible")
group.addToGroup(text)
scene.addItem(group)

# After this, text is no longer in group. However, it is no longer visible.
group.removeFromGroup(text)
assert not text in group.childItems()

# But text is still in scene.
assert text.scene() == scene

# this works (i.e. text becomes visible again). However, it also produces a
# warning: QGraphicsScene::addItem: item has already been added to this scene.
# The docs also advice against it.
scene.addItem(text)

# According to the docs, I thought this might work, but it gives me a TypeError.
# text.setParentItem(0)


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

非常欢迎提示和提示。

最佳答案

QGraphicsTextItem 永远不能作为场景的父级,因为它的父级必须是 QGraphicsItem(QGraphicsScene 不继承)。

创建 QGraphicsTextItem 时,它的父项是 None .它的父级设置为 group当它被添加到它时(QGraphicsItemGroup 是 QGraphicsItem 的子类),然后设置回 None当它从 group 中删除时.

调用 scene.addItem()实际上是一个 NO-OP。 Qt 检查是否scenetext.scene()相同,如果是,它会打印警告并返回而不执行任何操作。

它在某些情况下似乎“有效”的事实,只是 python 垃圾收集机制的产物。

如果您的测试以更真实的方式重播,QGraphicsTextItem 在从组中移除后仍然可见:

import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.view = QGraphicsView(self)
self.scene = QGraphicsScene(self.view)
self.view.setScene(self.scene)
self.setCentralWidget(self.view)
self.group = QGraphicsItemGroup()
self.text = QGraphicsTextItem()
self.text.setPlainText("I'm visible")
self.group.addToGroup(self.text)
self.scene.addItem(self.group)
self.group.removeFromGroup(self.text)

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

关于python - QGraphicsItemGroup.removeFromGroup——子项目没有正确地重新定位到场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21631909/

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