显示一个按钮,当点击时可以通过编程来调用一个确定的函数。
- setCheckable():设为true时识别按钮是按压还是释放
- toggle():在可选状态之间切换
- setIcon():显示图标
- setEnabled():当设为false时,按钮失效,因此点击时不会发射信号
- isChecked():返回按钮的布尔状态
- setDefault():设置按钮成为默认值
- setText():编写程序设置按钮的标题
- text():取回标题
主要就是clicked信号。
栗子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
import sys from PyQt4.QtCore import * from PyQt4.QtGui import *
class Form(QWidget): def __init__(self, parent=None): super(Form, self).__init__(parent)
self.button1 = QPushButton() self.button2 = QPushButton() self.button3 = QPushButton() self.button4 = QPushButton("&Default")
self.button1.setText(u"按钮1") self.button2.setText(u"按钮2") self.button3.setText(u"按钮3不可用") self.button4.setText(u"按钮4")
self.button1.setCheckable(True) self.button1.toggle() self.button1.clicked.connect(lambda:self.whichbtn(self.button1)) self.button1.clicked.connect(self.btnstate)
self.button2.setIcon(QIcon(QPixmap("Warcraft.png"))) self.button2.clicked.connect(lambda:self.whichbtn(self.button2))
self.button3.setEnabled(False)
self.button4.setDefault(True) self.button4.clicked.connect(lambda:self.whichbtn(self.button4))
layout = QVBoxLayout() layout.addWidget(self.button1) layout.addWidget(self.button2) layout.addWidget(self.button3) layout.addWidget(self.button4)
self.setLayout(layout)
def btnstate(self): if self.button1.isChecked(): print "button pressed" else: print "button released"
def whichbtn(self, b): print "clicked button is " + str(b.text().toUtf8())
def main(): app = QApplication(sys.argv) ex = Form() ex.show() sys.exit(app.exec_())
if __name__ == '__main__': main()
|