关于customContextMenuRequest连接调用的额外参数

时间:2015-07-31 21:52:04

标签: python pyqt pyqt4

我有一个不寻常的例子,在PyQt中定义与customContextMenuRequested插槽的连接时需要传递额外的参数。

当然,基本命令通常以以下形式完成:

myListWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
myListWidget.customContextMenuRequested.connect( self.Whatever_Popup )

我也知道并经常同时使用lambda和functools.partial 将额外参数传递给其他常规函数的方法。 但是,我有一个案例,我需要在定义连接时传递QObject(在这种情况下为listWidget)。

接收功能的结构如下:

def Whatever_Popup(self, pos):
    globalPos = self.mapToGlobal(pos)
    globalPos.setX( globalPos.x() + 720)
    globalPos.setY( globalPos.y() + 115)

    menu = QtGui.QMenu()
    menu.addAction("Edit")

    selectedItem = menu.exec_(globalPos)

    if selectedItem:
        if selectedItem.text() == "Edit":
            print "Here"
            #self.DoEdit(widget)

我尝试了以下所有内容,但没有任何快乐。

myListWidget.customContextMenuRequested.connect( partial(self.Whatever_Popup, newLst))

myListWidget.customContextMenuRequested.connect( partial(self.Whatever_Popup, QtCore.QPoint, newLst))

myListWidget.customContextMenuRequested.connect( partial(self.Whatever_Popup, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), newLst))

myListWidget.customContextMenuRequested.connect( lambda: self.Whatever_Popup, (QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), newLst) )

全部返回错误。我接近了吗?或者这可能不可能?这会有点令人惊讶。

动态生成

myListWidget btw。我需要传递一些参考 到listWidget因为self.DoEdit(widget)需要它进行进一步处理。无法预先定义名称并在self.DoEdit中检索它,因为它是动态创建的。 有人有解决方案吗? 感谢所有提前,

2 个答案:

答案 0 :(得分:0)

我偶然发现了答案,......必须重新排列接收函数参数,如下所示:

之前:

def Whatever_Popup(self, pos, widget):

后:

def Whatever_Popup(self, widget, pos):

答案 1 :(得分:0)

这里有一个有效的例子:

from functools import partial

from PyQt4.QtCore import Qt, QObject
from PyQt4.QtGui import QApplication, QMainWindow, QListWidget


class MainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)

        self.resize(800, 600)
        self.list_widget = QListWidget(self)
        self.list_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        my_object = QObject()
        self.list_widget.customContextMenuRequested.connect(
            partial(self.receiver, my_object))

        self.setCentralWidget(self.list_widget)

    def receiver(self, my_object, pos):
        pass


if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

my_object替换为您需要的任何内容。

希望它有所帮助。

相关问题