import sys

import sip
sip.setapi('QString', 2)
sip.setapi('QTextStream', 2)
# XXX: Works when not using QVariant API 2.
sip.setapi('QVariant', 2)

from PyQt4 import QtCore, QtGui


class TestProxy(QtGui.QGraphicsProxyWidget):
   """
   Simple QGraphicsProxy that tries to handle certain itemChange() events.
   """
   def __init__(self, parent = None):
      QtGui.QGraphicsProxyWidget.__init__(self, parent, QtCore.Qt.Window)
      self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)

      self._panel  = QtGui.QWidget()

      self._layout = QtGui.QVBoxLayout()
      self._panel.setLayout(self._layout)

      self._addChildBtn = QtGui.QPushButton("Add Child")
      self._closeBtn    = QtGui.QPushButton("Close")
      self._layout.addWidget(self._addChildBtn)
      self._layout.addWidget(self._closeBtn)

      # Connect signals.
      self._addChildBtn.clicked.connect(self._onAddChild)
      self._closeBtn.clicked.connect(self._onClosed)

      spacer_item = QtGui.QSpacerItem(40, 10, QtGui.QSizePolicy.Minimum,
                                      QtGui.QSizePolicy.MinimumExpanding)
      self._layout.addItem(spacer_item)

      self._panel.resize(200, 200)
      self.setWidget(self._panel)

   def itemChange(self, eventType, value):
      # XXX: It appears that when this is ItemParentChange the QVariant
      #      conversion does not work.
      return QtGui.QGraphicsProxyWidget.itemChange(self, eventType, value)

   def _onAddChild(self, checked = False):
      child = TestProxy()
      child.setParentItem(self)
      child.setPos(100.0, 100.0)

   def _onClosed(self, checked = False):
      self.close()


if "__main__" == __name__:
   app = QtGui.QApplication(sys.argv)

   scene = QtGui.QGraphicsScene(0, 0, 600, 600)
   view = QtGui.QGraphicsView(scene)

   # Give the view a better default size.
   view.show()

   proxy = TestProxy()
   scene.addItem(proxy)
   proxy.setPos(200.0, 200.0)

   sys.exit(app.exec_())
