yas*_*sar 9 python pyqt signals-slots
我在工具栏中有大约10个QAction(这个数字在运行时会有所不同),它们都会做同样的事情,但是使用不同的参数.我想将参数作为属性添加到QAction对象,然后,QAction的触发信号也会将对象本身发送到回调函数,这样我就可以得到函数所需的参数.我实际上有两个问题:
rec*_*dev 41
如何在PyQt中将参数传递给回调函数
您可以使用functools.partial标准的Python库.示例QAction:
some_action.triggered.connect(functools.partial(some_callback, param1, param2))
Run Code Online (Sandbox Code Playgroud)
Dom*_*rrs 11
您可以使用与GUI控件的槽相关联的lambda函数将额外的参数传递给您要执行的方法.
# Create the build button with its caption
self.build_button = QPushButton('&Build Greeting', self)
# Connect the button's clicked signal to AddControl
self.build_button.clicked.connect(lambda: self.AddControl('fooData'))
def AddControl(self, name):
print name
Run Code Online (Sandbox Code Playgroud)
来源:snip2code - 使用Lambda函数在PyQt4中传递额外参数
您可以使用信号映射器发送操作对象本身。然而,最好只是发送一个标识符并在信号处理程序中完成所有工作。
这是一个简单的演示脚本:
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.mapper = QtCore.QSignalMapper(self)
self.toolbar = self.addToolBar('Foo')
self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
for text in 'One Two Three'.split():
action = QtGui.QAction(text, self)
self.mapper.setMapping(action, text)
action.triggered.connect(self.mapper.map)
self.toolbar.addAction(action)
self.mapper.mapped['QString'].connect(self.handleButton)
self.edit = QtGui.QLineEdit(self)
self.setCentralWidget(self.edit)
def handleButton(self, identifier):
if identifier == 'One':
text = 'Do This'
elif identifier == 'Two':
text = 'Do That'
elif identifier == 'Three':
text = 'Do Other'
self.edit.setText(text)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.resize(300, 60)
window.show()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14937 次 |
| 最近记录: |