如何在QTreeWidget的上下文菜单中发送信号?

时间:2015-12-09 10:04:19

标签: python-3.x pyqt pyside


您好我在Windows 7中使用python3.4,PyQt5制作桌面GUI应用程序。我已经制作了一个简单的QTreeWidget。我添加了一个上下文菜单。

我的参考代码是这个(https://wiki.python.org/moin/PyQt/Creating%20a%20context%20menu%20for%20a%20tree%20view

参考代码效果很好。当我在QTreeWidgetItem上单击鼠标右键时,会弹出上下文菜单。

但是当用户点击上下文菜单时,我不知道如何发出信号。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

使用相同的示例并在事件中添加了QAction。正如tmoreau所说,你需要很好地阅读文档:)

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from functools import partial

data = [
    ("Alice", [
        ("Keys", []),
        ("Purse", [
            ("Cellphone", [])
            ])
        ]),
    ("Bob", [
        ("Wallet", [
            ("Credit card", []),
            ("Money", [])
            ])
        ])
    ]

class Window(QWidget):

    def __init__(self):

        QWidget.__init__(self)

        self.treeView = QTreeView()
        self.treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.treeView.customContextMenuRequested.connect(self.openMenu)

        self.model = QStandardItemModel()
        self.addItems(self.model, data)
        self.treeView.setModel(self.model)

        self.model.setHorizontalHeaderLabels([self.tr("Object")])

        layout = QVBoxLayout()
        layout.addWidget(self.treeView)
        self.setLayout(layout)

    def addItems(self, parent, elements):

        for text, children in elements:
            item = QStandardItem(text)
            parent.appendRow(item)
            if children:
                self.addItems(item, children)

    def openMenu(self, position):

        indexes = self.treeView.selectedIndexes()
        if len(indexes) > 0:

            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level += 1

        menu = QMenu()
        editMenu = None
        if level == 0:
            editMenu = QAction("Edit person", self)
            menu.addAction(editMenu)
        elif level == 1:
            editMenu = QAction("Edit object/container", self)
            menu.addAction(editMenu)
        elif level == 2:
            editMenu = QAction("Edit object", self)
            menu.addAction(editMenu)

        if editMenu:
            editMenu.triggered.connect(partial(self.editObjFunc, level))

        menu.exec_(self.treeView.viewport().mapToGlobal(position))

    def editObjFunc(self, level):
        print level


if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())