python - 通过 PyQt 中 QTableView 和 QTableWidget 的上下文菜单传递实例

标签 python python-2.7 qt pyqt pyqt4

呃,好吧, friend 们,现在我正在尝试为我的应用程序中的每个表格添加“导出到 Excel”功能,如下所示:

...
def update_exportable_tables(self, *window):
    """
    Please don't ask why, here 'I know what I'm doing'
    """
    if not window:
        window = self.window

    for obj in window.__dict__:
        objname = obj.title().lower()
        the_object_itself = window.__dict__[obj]

        if isinstance(the_object_itself, (QTableWidget, QTableView)):
            the_object_itself.setContextMenuPolicy(Qt.CustomContextMenu)
            the_object_itself.customContextMenuRequested.connect(self.TableContextEvent)


def TableContextEvent(self, event):
    menu = QMenu()
    excelAction = menu.addAction(u"Export to Excel")
    excelAction.triggered.connect(self.export)
    action = menu.exec_(QCursor.pos())

def export(self):
    print 'Here I should do export'
...

是的,它工作正常,但是......问题是我应该如何将单击的表实例传递给我的export()函数?

最佳答案

有几种不同的方法可以解决这个问题。这是一种方法:

def update_exportable_tables(self):
    for widget in QtGui.qApp.allWidgets():
        if isinstance(widget, QTableView):
            widget.setContextMenuPolicy(Qt.CustomContextMenu)
            widget.customContextMenuRequested.connect(self.showContextMenu)

def showContextMenu(self, pos):
    table = self.sender()
    pos = table.viewport().mapToGlobal(pos)
    menu = QtGui.QMenu()
    excelAction = menu.addAction("Export to Excel")
    if menu.exec_(pos) is excelAction:
        self.export(table)

def export(self, table):
    print 'Here I should do export:', table

(注意:QTableWidgetQTableView 的子类)。

关于python - 通过 PyQt 中 QTableView 和 QTableWidget 的上下文菜单传递实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477127/

相关文章:

Python Pandas 使用 Fastparquet 将 CSV 转换为 Parquet

python - 按字母顺序查找最长的子串。我的代码有什么问题

python - 无法弄清楚如何使用 all() 在我的 "code"中工作

Python 使用正则表达式解析 HTML

c++ - 在 Qt 的 OpenGL 中启用立体 View

c++ - 将 QML 事件传播到 C++

c++ - Qt Directx 渲染

python - 如何使用python将表单数据插入MYSQL

python - 在 Linux 上安装 MySQLdb 失败

python - 修复 Python requests.exception.InvalidURL : Invalid percent-escape sequence 'u2' error?