直接上例子:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
layout = QVBoxLayout() #布局
self.b1 = QPushButton("Button1") #添加按钮
self.b1.setCheckable(True) # 识别b1的状态
self.b1.toggle() # 在状态之间切换
self.b1.clicked.connect(lambda:self.whichbtn(self.b1)) # 发射clicked信号并连接下面的whichbtn槽函数,此处可以传递b1这个参数进去
self.b1.clicked.connect(self.btnstate) # 发射clicked信号并连接下面的btnstate槽函数
layout.addWidget(self.b1) #布局套路
self.b2 = QPushButton()
self.b2.setIcon(QIcon(QPixmap("python.gif"))) # b2设置图标
self.b2.clicked.connect(lambda:self.whichbtn(self.b2))
layout.addWidget(self.b2)
self.setLayout(layout)
self.b3 = QPushButton("Disabled") # b3不可按
self.b3.setEnabled(False)
layout.addWidget(self.b3)
self.b4 = QPushButton("&Default") # 名称中加上前缀&,这样就可以使用快捷键Alt+D来点击该按钮
self.b4.setDefault(True)
self.b4.clicked.connect(lambda:self.whichbtn(self.b4))
layout.addWidget(self.b4)
self.setWindowTitle("Button demo")
def btnstate(self):
if self.b1.isChecked():
print "button pressed"
else:
print "button released"
def whichbtn(self,b):
print "clicked button is "+b.text()
def main():
app = QApplication(sys.argv)
ex = Form()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
这是按钮点击的一种写法,还有一种是:
QtCore.QObject.connect(button, QtCore.SIGNAL(‘clicked()’),self.onClicked)