0

我试图让我的代码与多个 listViews 一起工作,而不仅仅是一个,但我遇到了问题。

一份清单的工作代码:

Class Ui_MainWindow(QtGui.QMainWindow):
    def itemDropped(self, links):
        item = QtGui.QListWidgetItem(url, self.listView)
    def setupUi(self, MainWindow):
        self.connect(self.listView, QtCore.SIGNAL("dropped"), self.itemDropped)  

Class TestListView(QtGui.QListWidget):
    def dropEvent(self, event):
        self.emit(QtCore.SIGNAL("dropped"), links)

到目前为止,我使用多个列表:

Class Ui_MainWindow(QtGui.QMainWindow):
    def itemDropped(self, links, listName):
        item = QtGui.QListWidgetItem(url, listName)
    def setupUi(self, MainWindow):
        self.connect(self.listView, QtCore.SIGNAL("dropped"), self.itemDropped(self.listView))  

Class TestListView(QtGui.QListWidget):
    def dropEvent(self, event):
        self.emit(QtCore.SIGNAL("dropped"), links)

所以我收到“self.itemDropped(self.listView)”的错误,在研究了这里和其他网站后,我想出了这个:

self.connect(self.listView, QtCore.SIGNAL("dropped"),(lambda : self.itemDropped(self.listView)))

我以前从未使用过 lambda 函数,因为我对 python 还很陌生,但这确实解决了这个问题,当我打印 listName 时它会正确显示。现在的问题是链接没有从其他类正确发出,或者我没有正确接收它们。

所以我想pseduocode我需要这样的东西:

self.connect(self.listView, QtCore.SIGNAL("dropped"),(lambda : self.itemDropped(X, self.listView)))

问题是我如何获得 X,即来自 TestListView 类的链接?当没有变量传递给函数时,我不太明白我是如何只用 1 个列表接收它们的。

感谢你们提供的任何帮助,我非常感谢。如果您想要更大的图片,这里的 Ps 代码可能看起来很熟悉PyQT4:将文件拖放到 QListWidget

4

1 回答 1

1

你想要的是这个

self.connect(self.listView, QtCore.SIGNAL("dropped"),(lambda X: self.itemDropped(X, self.listView)))

当您发出信号时,您将links变量传递到插槽中,该插槽曾经是self.itemDropped(其签名是self.itemDropped (links))。

相反,您的 slot 现在是一个 lambda 函数,因此您需要通过以lambda X:. 然后,这X可用于 lambda 定义的其余部分。

当您的信号发出时,您的 lambda 函数被调用并X包含links.

一般来说: def foo(x): do_something(x) foo(3)

相当于 my_function = lambda x: do_something(x) my_function(3)

有道理?

EDIT: I should also point out (for any future applications you have) that there are some tricky points when using variables inside lambda functions (specifically the use of variables that are not specified in the definition of the lambda function, such as the use of self.listView). When the lambda function is called (when the signal is emitted), it will use whatever the current value of self.listView is, not the value it was when the function was defined. This becomes a problem when defining lambda functions inside a loop and trying to use a loop variable inside your lambda function. Some useful information can be found here (read the comments too) http://eli.thegreenplace.net/2011/04/25/passing-extra-arguments-to-pyqt-slot/

于 2013-01-20T08:04:22.427 回答