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

问题描述 投票:0回答:2

呃,好吧,朋友们,现在我正在尝试为我的应用程序中的每个表格添加“导出到 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()函数?

python python-2.7 pyqt qtableview qtablewidget
2个回答
3
投票

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

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

(注意:

QTableWidget
QTableView
的子类)。


0
投票

好的,感谢 Eli Bendersky,我在谷歌上搜索了一种方法。

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

def TableContextEvent(self, table_instance):
    print table_instance
    #     ^^^^^^^^^^^^^ And yes, we have it!

upd1:它仍然是错误的,因为仅连接到一个实例(只有最后一个表实例在各处传递)

© www.soinside.com 2019 - 2024. All rights reserved.