combo.activated[str].connect(self.onActivated)' 中括号的含义是什么?

5 投票
2 回答
1200 浏览
提问于 2025-04-18 07:29

在一个 pyside 教程 中,我看到 QtGui.QComboBox 示例里有这么一行:

combo.activated[str].connect(self.onActivated)  

在这个上下文中,[str] 这个表达式是什么意思呢?这个例子里没有解释,pyside 文档 上也没有说明。而且从原始的 Qt 文档 看来,[str] 这个表达式到底是什么意思也不太清楚。

我对列表和字典的索引是很了解的,但在这个上下文中,似乎是对一个类的方法进行了索引。

2 个回答

0

[str] 表示传递给你的处理函数的参数将会是字符串类型。你可以在这里查看详细信息:http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html#connecting-disconnecting-and-emitting-signals

5

这里,activated 是一个 重载信号,而 [str] 是用来索引到 str 类型的重载。

信号之所以被称为 重载,就像在 C++ 中函数重载的原因一样:有两个同名的函数,但它们接受不同的参数:

void QComboBox::activated ( int index ) [signal]
void QComboBox::activated ( const QString & text ) [signal]

Python 并没有像 C++ 那样严格的函数重载机制。因此,PyQt 通过维护一个插槽的字典来处理这个问题,你可以将信号连接到这些插槽。这个字典的键是你的处理函数可以接受的参数类型。

页面上这个 wastl 链接的例子 描述得很好:

from PyQt4.QtGui import QComboBox

class Bar(QComboBox):

    def connect_activated(self):
        # The PyQt4 documentation will define what the default overload is.
        # In this case it is the overload with the single integer argument.
        self.activated.connect(self.handle_int)

        # For non-default overloads we have to specify which we want to
        # connect.  In this case the one with the single string argument.
        # (Note that we could also explicitly specify the default if we
        # wanted to.)
        self.activated[str].connect(self.handle_string)

    def handle_int(self, index):
        print "activated signal passed integer", index

    def handle_string(self, text):
        print "activated signal passed QString", text

进一步阅读:

撰写回答