2

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.

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).

My most sincere thanks, as always, for any assistance you can provide.

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_()) 
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
maurobio
  • 1,480
  • 4
  • 27
  • 38

1 Answers1

2

To obtain the selected element we use the {your QTreeWidget}.selectedItems() function that returns the selected elements.

In your case the selection should be of mode: SingleSelection.

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)

        self.tree.setSelectionMode(QAbstractItemView.SingleSelection)

        insertKey = QShortcut(QKeySequence(Qt.Key_Insert), self.tree)
        insertKey.activated.connect(self.itemInsert)
        editKey = QShortcut(QKeySequence(Qt.Key_Return), self.tree)
        editKey.activated.connect(self.itemEdit)
        self.setCentralWidget(self.tree)
        self.tree.setHeaderLabel('Tree')
        i = QTreeWidgetItem(self.tree, ['Parent'])
        self.tree.addTopLevelItem(i)
        for x in range(5):
            QTreeWidgetItem(i, ['Child {}'.format(x)])

    def itemInsert(self):
        text, ok = QInputDialog.getText(self, "Add Child", "Enter child name:")
        if ok and text != "":
            if len(self.tree.selectedItems()) > 0:
                QTreeWidgetItem(self.tree.selectedItems()[0], [text])
            else:
                QTreeWidgetItem(self.tree, [text])

    def itemEdit(self):
        if self.tree.selectedItems():
            item = self.tree.selectedItems()[0]
            text, ok = QInputDialog.getText(self, "Edit Child", "Modify name:", QLineEdit.Normal, item.text(0))
            if ok and text != "":
                item.setText(0, text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ui = MyMainWindow()
    ui.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241