combo.activated[str].connect(self.onActivated)' 中括号的含义是什么?
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
进一步阅读:
- PyQt 和信号重载 (Blogspot)
- 使用新样式语法连接重载的 PyQT 信号 (Stack Overflow)