使用lambda传递参数到槽函数
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__();
self.initUI()
def initUI(self):
self.button = QtGui.QPushButton("print clicked",self)
self.clicked='not_clicked'
self.button.clicked.connect(lambda opt='clicked': self.option(opt))
def option(self,opt):
self.clicked=opt
print opt
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()
看看这段代码。当我点击“打印点击”这个按钮时,控制台上会显示‘False’(在选项函数里)。这是为什么呢?
1 个回答
1
QPushButton
这个按钮类是从QAbstractButton
这个类继承来的。
在Qt的文档中提到:
void QAbstractButton::clicked ( bool checked = false ) [signal]
这个信号会在按钮被激活时发出(也就是当你按下按钮然后在鼠标光标还在按钮上时松开),或者当你输入快捷键,或者调用click()或animateClick()时发出。需要注意的是,如果你调用setDown()、setChecked()或toggle(),这个信号是不会被发出的。
如果这个按钮是可选中的,那么checked的值为true表示按钮被选中了,false表示按钮没有被选中。
槽函数接收到的参数表示按钮是否被选中。因为QPushButton
默认情况下不是可选中的,所以这个参数总是False
。这就是为什么打印出来的是'False'。
如果你想让打印的结果有所不同,打印出'True'或'False',你可以把按钮设置为checkable
,或者把它换成QCheckBox
。
例如,initUI
应该是
def initUI(self):
self.button = QtGui.QCheckBox("print clicked",self)
self.button.setCheckable(True)
self.clicked='not_clicked'
self.button.clicked.connect(lambda opt='clicked': self.option(opt))
或者
def initUI(self):
#self.button = QtGui.QPushButton("print clicked",self)
self.button = QtGui.QCheckBox("print clicked",self)
self.clicked='not_clicked'
self.button.clicked.connect(lambda opt='clicked': self.option(opt))