sending QTreeWidgetItem to a function with python
Question: I'm trying to make a program using Python, Komodo and QT4.

I'm trying to send a QTreeWidgetItem to a function after it was selected by
the user with the mouse. All I was able to do is to move the position of the X
and Y of the selected point by the mouse. Can anybody tell me how to send an
QTreeWidgetItem to a function?

This is my code:

    
    
    from PyQt4 import QtCore, QtGui
    
    try:
        _fromUtf8 = QtCore.QString.fromUtf8
    except AttributeError:
        def _fromUtf8(s):
            return s
    
    try:
        _encoding = QtGui.QApplication.UnicodeUTF8
        def _translate(context, text, disambig):
            return QtGui.QApplication.translate(context, text, disambig, _encoding)
    except AttributeError:
        def _translate(context, text, disambig):
            return QtGui.QApplication.translate(context, text, disambig)
    
    class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
            MainWindow.setObjectName(_fromUtf8("MainWindow"))
            MainWindow.resize(800, 600)
            self.centralwidget = QtGui.QWidget(MainWindow)
            self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
            self.treeWidget = QtGui.QTreeWidget(self.centralwidget)
            self.treeWidget.setGeometry(QtCore.QRect(155, 50, 481, 361))
            self.treeWidget.setObjectName(_fromUtf8("treeWidget"))
            MainWindow.setCentralWidget(self.centralwidget)
            self.menubar = QtGui.QMenuBar(MainWindow)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
            self.menubar.setObjectName(_fromUtf8("menubar"))
            MainWindow.setMenuBar(self.menubar)
            self.statusbar = QtGui.QStatusBar(MainWindow)
            self.statusbar.setObjectName(_fromUtf8("statusbar"))
            MainWindow.setStatusBar(self.statusbar)
            self.create_popup_menu()
            self.treeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
            self.treeWidget.customContextMenuRequested.connect(self.on_context_menu)
            string="default,default:cluster1,default:cluster1:clusterA,default:cluster2,default:cluster2:clusterA"
            self.retranslateUi(MainWindow)
            self.buildingTree(string)
            QtCore.QMetaObject.connectSlotsByName(MainWindow)
    
        def retranslateUi(self, MainWindow):
            MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
            self.treeWidget.headerItem().setText(0, _translate("MainWindow", "Assignment1", None))
            __sortingEnabled = self.treeWidget.isSortingEnabled()
    
        def buildingTree(self, string):
            arrTree = []
            arrPath = []
            arrString = []
            arrString = string.split(",")
            root = QtGui.QTreeWidgetItem(self.treeWidget)
            root.setText(0,arrString[0])
            arrTree.append(root)
            arrString.pop(0)
            for path in arrString:
                arrPath = path.split(":")
                nameOfFather = arrPath[len(arrPath)-2]
                arrTree.reverse()
                for node in arrTree:
                    nameOfNode = node.text(0)
                    if nameOfNode == nameOfFather:
                        sonNode = QtGui.QTreeWidgetItem(node)
                        sonNode.setText(0,arrPath[len(arrPath)-1])
                        arrTree.insert(0,sonNode)
                        arrTree.reverse()
                        break
            self.treeWidget.setSortingEnabled(False)        
    
        def new_cluster(self):
            print "New Cluster"
    
        def rename_cluster(self):
            print "Rename cluster"
    
        def delete_cluster(self):
            print "Delete cluster"
    
        def create_popup_menu(self, parent=None):
            self.popup_menu = QtGui.QMenu(parent)
            self.popup_menu.addAction("New", self.new_cluster)
            self.popup_menu.addAction("Rename", self.rename_cluster)
            self.popup_menu.addSeparator()
            self.popup_menu.addAction("Delete", self.delete_cluster)
    
        def on_context_menu(self, pos):
            print "open menu"
            position = QtGui.QTreeWidgetItem(self.treeWidget)
            print position
            position = pos
            print position
            print "%%%%%%%%%%%%%%%"
            """
            node = self.treeWidget.itemAt(position)
            print node
            node = self.treeWidget.setCurrentItem(node)
            print node.text(0)
            self.popup_menu.exec_(self.treeWidget.mapToGlobal(pos))
    
            global_pos = self.mapToGlobal(pos)
            t = self.itemAt(pos)
            self.setCurrentItem(t)
            """
    
    if __name__ == "__main__":
        import sys
        app = QtGui.QApplication(sys.argv)
        MainWindow = QtGui.QMainWindow()
        ui = Ui_MainWindow()
        ui.setupUi(MainWindow)
        MainWindow.show()
        sys.exit(app.exec_())
    


Answer: Your code is very unclear, because you are editing the file generated by
`pyuic`, rather than importing it into your main application.

I have re-structured your code, and used an [event filter](https://qt-
project.org/doc/qt-4.8/qobject.html#installEventFilter) to handle the context-
menu, which helps simplify the code a little. I have also used `lambda`
functions to handle the menu actions. The code below assumes the file from
`pyuic` is saved as `mainwindow_ui.py` (which you will obviously need to re-
generate).

    
    
    from PyQt4 import QtCore, QtGui
    from mainwindow_ui import Ui_MainWindow
    
    class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.setupUi(self)
            self.buildingTree(
                "default,default:cluster1,default:cluster1:clusterA,"
                "default:cluster2,default:cluster2:clusterA"
                )
            self.treeWidget.viewport().installEventFilter(self)
    
        def eventFilter(self, target, event):
            if (event.type() == QtCore.QEvent.ContextMenu and
                target is self.treeWidget.viewport()):
                item = self.treeWidget.itemAt(event.pos())
                if item is not None:
                    menu = QtGui.QMenu()
                    menu.addAction(
                        "New", lambda: self.new_cluster(item))
                    menu.addAction(
                        "Rename", lambda: self.rename_cluster(item))
                    menu.addSeparator()
                    menu.addAction(
                        "Delete", lambda: self.delete_cluster(item))
                    menu.exec_(event.globalPos())
                return True
            return super(MainWindow, self).eventFilter(target, event)
    
        def new_cluster(self, item):
            print "New Cluster", item.text(0)
    
        def rename_cluster(self, item):
            print "Rename cluster", item.text(0)
    
        def delete_cluster(self, item):
            print "Delete cluster", item.text(0)
    
        def buildingTree(self, string):
            arrTree = []
            arrPath = []
            arrString = []
            arrString = string.split(",")
            root = QtGui.QTreeWidgetItem(self.treeWidget)
            root.setText(0,arrString[0])
            arrTree.append(root)
            arrString.pop(0)
            for path in arrString:
                arrPath = path.split(":")
                nameOfFather = arrPath[len(arrPath)-2]
                arrTree.reverse()
                for node in arrTree:
                    nameOfNode = node.text(0)
                    if nameOfNode == nameOfFather:
                        sonNode = QtGui.QTreeWidgetItem(node)
                        sonNode.setText(0,arrPath[len(arrPath)-1])
                        arrTree.insert(0,sonNode)
                        arrTree.reverse()
                        break
            self.treeWidget.setSortingEnabled(False)
    
    if __name__ == "__main__":
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())
    

