在初始化期间,您可以向QObject传递什么类型的KWARG?

2024-05-29 10:57:19 发布

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

我注意到,在PyQt5中,初始化QObject时,可以根据对象传递关键字来建立某些连接。我认为这是非常有用的,因为它不仅为您节省了第二条语句,因此如果不需要,您也不需要显式引用对象,但更重要的是,在某些情况下,这样做可能会非常麻烦。例如,如果你想创建一个对象列表,它可以为你保存一个循环等等

例如,在QActions的情况下,您可以这样做:

from PyQt5.QtWidgets import QAction
from PyQt5.QtCore import pyqtSlot


@pyqtSlot()
def do_something():
    pass


@pyqtSlot()
def do_something_else():
    pass


actions = [QAction(triggered=do_something), QAction(triggered=do_something_else)]

但我只是偶然发现了这种行为。我在任何地方都找不到记录。例如,在正式的Qt文档中,没有提到任何关键字(QObjectQAction)。在初始化期间,您是否可以使用QObjects执行更多类似的操作

我不明白为什么没有记录下来。不推荐吗?我使用PyCharm作为编辑器,尽管我知道它在语法检查方面存在问题,especially with regards to PyQt,但它也将这些关键字作为“意外参数”突出显示


Tags: 对象fromimportdef情况pass关键字do
1条回答
网友
1楼 · 发布于 2024-05-29 10:57:19

PyQt5 docsSupport for Qt Properties节中,指出哪种类型的数据支持关键字参数:

PyQt5 does not support the setting and getting of Qt properties as if they were normal instance attributes. This is because the name of a property often conflicts with the name of the property’s getter method.

However, PyQt5 does support the initial setting of properties using keyword arguments passed when an instance is created. For example:

act = QAction("&Save", self, shortcut=QKeySequence.Save,
        statusTip="Save the document to disk", triggered=self.save) 

The example also demonstrates the use of a keyword argument to connect a signal to a slot.

PyQt5 also supports setting the values of properties (and connecting a signal to a slot) using the pyqtConfigure() method. For example, the following gives the same results as above:

act = QAction("&Save", self)
act.pyqtConfigure(shortcut=QKeySequence.Save,
        statusTip="Save the document to disk", triggered=self.save)

(强调矿山)

总之,您可以设置kwargs:

  • QProperty的初始化,以及
  • 与信号相连的插槽

相关问题 更多 >

    热门问题