0%

PyQt4--《八》单选框QCheckBox

文字标签之前的矩形框,是多选按钮。
多选按钮默认是不排他的,如果想要手动排他,需要将这些复选框放入QButtonGroup中。

QCheckBox的函数

  • setChecked():更改按钮状态
  • setText():设置标签
  • text():取回标题
  • isChecked():查看是否被勾选
  • setTriState():提供无状态变化

QCheckBox的信号

有toggled()信号。还有stateChanged()信号,每次复选框勾选或清除时,都会发射该信号。

栗子

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
#-*-coding:utf-8-*-
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class window(QWidget):
def __init__(self, parent=None):
super(window, self).__init__(parent)
self.init()

def init(self):
# 创建对象
layout = QHBoxLayout()
self.button1 = QCheckBox()
self.button2 = QCheckBox()

# 设置对象属性
self.button1.setText(u"按钮1")
self.button1.setChecked(True)
self.button1.stateChanged.connect(lambda :self.btnstate(self.button1))# 发射stateChanged信号,这里调用与button2一样

self.button2.setText(u"按钮2")
self.button2.toggled.connect(lambda :self.btnstate(self.button2))

# 添加对象到容器
layout.addWidget(self.button1)
layout.addWidget(self.button2)
self.setLayout(layout)
self.setWindowTitle(u"复选框demo")

def btnstate(self, b):
if str(b.text().toUtf8()) == "按钮1":
if b.isChecked() == True:
print str(b.text().toUtf8()) + " is selected"
else:
print str(b.text().toUtf8()) + " is deselected"

if str(b.text().toUtf8()) == "按钮2":
if b.isChecked() == True:
print str(b.text().toUtf8()) + " is selected"
else:
print str(b.text().toUtf8()) + " is deselected"

def main():
app = QApplication(sys.argv)
ex = window()
ex.show()
sys.exit(app.exec_())


if __name__ == '__main__':
main()