title: PyQt: Adding children to TreeWidget dynamically
body: <p>I have a TreeWidget with one or more parents, each of which has a variable number of children. The tree is initially populated (say, with data from a database in a real application). I would like that a user could be able to add one or more children to each parent, as well as to edit the currently selected children, but cannot figure out how to to this.</p>
  
  <p>Below is my sample code, which builds a tree with a parent and five children. The form intercepts the "Return" and "Ins" keys and invokes a simple data entry dialog for getting the text to be entered as a new child or editing the currently selected child. Here I struck to two problems: First, how to get the text of the currently selected child for editing? Second, how to as the input text as a new child (in the sample code, I have been able only to add the entered text at the parent level of the tree).</p>
  
  <p>My most sincere thanks, as always, for any assistance you can provide.</p>
  
  <pre><code>import sys
  from PyQt4.QtCore import * 
  from PyQt4.QtGui import *
  
  class MyMainWindow(QMainWindow):
      def __init__(self, parent=None):
          super(MyMainWindow, self).__init__(parent)
          self.tree = QTreeWidget(self)
          insertKey = QShortcut(QKeySequence(Qt.Key_Insert), self.tree)
          self.connect(insertKey, SIGNAL("activated()"), self.itemInsert)
          editKey = QShortcut(QKeySequence(Qt.Key_Return), self.tree)
          self.connect(editKey, SIGNAL("activated()"), self.itemEdit)
          self.setCentralWidget(self.tree)
          self.tree.setHeaderLabel('Tree')
          i = QTreeWidgetItem(self.tree, ['Parent'])   
          self.tree.addTopLevelItem(i)
          for x in range(5):
              j = QTreeWidgetItem(i ,['Child {}'.format(x)])
  
      def itemInsert(self):
          text, ok = QInputDialog.getText(self, "Add Child", "Enter child name:")
          if ok and not text.isEmpty():
              child = QTreeWidgetItem(self.tree, [text])
  
      def itemEdit(self):
          pass
  
  if __name__ == "__main__":
      app = QApplication(sys.argv)
      ui = MyMainWindow()
      ui.show()
      sys.exit(app.exec_()) 
  </code></pre>