我在哪里可以找到PyQt5方法签名?

时间:2014-12-14 13:42:22

标签: python-3.x pyqt5 method-signature keyword-argument

我想用图形用户界面编写一个小应用程序,为此我安装了PyQt5。在一个教程中,我发现了一个QMessageBox.information(....)调用已完成。

我想更改通话,而不是:

QMessageBox.information(self, "Empty Field", "Please enter a name and address.")

我写关键字参数,以便我知道哪些参数代表哪些内容,因此,当我在一年内阅读它时,我立即知道它是什么。所以我试过了:

QMessageBox.information(parent=self, title="Empty Field", message="Please enter a name and address.")

在执行时出现以下错误:

Traceback (most recent call last):
File "SimpleExample.py", line 39, in submitContact
QMessageBox.information(parent=self, title="Empty Field", message="Please enter a name and address.")
TypeError: QMessageBox.information(QWidget, str, str, QMessageBox.StandardButtons buttons=QMessageBox.Ok, QMessageBox.StandardButton defaultButton=QMessageBox.NoButton): 'message' is not a valid keyword argument

所以我的猜测是错误的,但我如何找出真正的方法签名? 我搜索了一会儿,发现了这个功能:

from inspect import getcallargs
getcallargs()

我尝试过这样使用它:

>>> from inspect import getcallargs
>>> from PyQt5.QtWidgets import *
>>> from PyQt5.QtCore import *
>>> getcallargs(QMessageBox.information(), a=1, b=2)

但这也行不通:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: QMessageBox.information(QWidget, str, str, QMessageBox.StandardButtons buttons=QMessageBox.Ok, QMessageBox.StandardButton defaultButton=QMessageBox.NoButton): not enough arguments

无论我添加多少个参数(函数1,2,3,4,5,6,7,8,...),它都不是足够的参数。如果它正在讨论information()的参数,那么我应该如何找到我想要获取参数的函数的正确数量的参数?!

所以我想“好吧,试试看我是否可以在Qt5文档中找到该方法。”但是当然,在那里我只被重定向到Qt5的c ++文档,而且没有为QMessageBox列出函数“information()”,所以我仍然不知道关键字的名称。

我怎样才能找出这些名字?

1 个答案:

答案 0 :(得分:3)

在PyQt中,只有可选参数支持关键字参数,因此不能将它们用作记录函数签名的一般方法。

获取正确方法签名的一种快捷方法是在python交互式会话中使用help函数:

>>> from PyQt5 import Qt
>>> help(Qt.QMessageBox.information)
...

Help on built-in function information:

information(...)
    QMessageBox.information(QWidget, str, str, QMessageBox.StandardButtons buttons=QMessageBox.Ok, QMessageBox.StandardButton defaultButton=QMessageBox.NoButton) -> QMessageBox.StandardButton

这表明只有buttonsdefaultButton可用作关键字参数。

执行此操作非常重要,而不是查看QMessageBox.​information的Qt文档,因为无法保证C ++参数名称与PyQt使用的名称相匹配(有关详细信息,请参阅{{ 3}}在PyQt Docs中。