【发布时间】:2014-02-08 03:34:26
【问题描述】:
我正在尝试从 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_())
非常欢迎提示和提示。
【问题讨论】:
-
在添加到组之前尝试将文本项添加到场景中
-
感谢您的建议,但(至少在这里)没有什么不同。
-
从组中移除后尝试设置项目的位置。