0%

PyQt4--《七》单选框QRadioButton

显示一个带有文字标签的可选按钮,可在表单中选择某一个选项,是单选按钮。该类派生自QAbstractButton。
单选按钮默认是排他的,即一次只能选择一个选项。可以把Radio Button放入QGroupBox或QButtonGroup中以创建更多可选的选项。

QRadioButton的函数

  • setChecked():更改单选按钮的状态
  • setText():设置与按钮相关联的标签
  • text():取得按钮的标题
  • isChecked():检查按钮是否被选择

QRadioButton的信号

默认信号是toggled(),也可以使用从QAbstractButton类中继承的其他信号。

栗子

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
#-*-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):
#创建对象
self.button1 = QRadioButton()
self.button2 = QRadioButton()
layout = QHBoxLayout()

#设置对象属性
self.button1.setText(unicode("按钮1","utf8"))
self.button2.setText(unicode("按钮2","utf8"))
self.button1.setChecked(True)#按钮1为默认选中状态
self.button1.toggled.connect(lambda :self.btnstate(self.button1))# 发射toggled信号,连接btnstate槽函数
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()