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

2024-09-30 02:26:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: theselfobjifobjectdefconnectexport
2条回答

好吧,多亏了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:仍然错误,因为只连接到一个实例(只有最后一个表实例在所有地方传递)

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

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的一个子类)。在

相关问题 更多 >

    热门问题