例子
这里两个互斥的单选按钮构建在顶层窗口上。
b1 的默认状态由语句设置为检查 -
两个按钮的 toggled() 信号都连接到 btnstate() 函数。使用 lambda 允许将信号源作为参数传递给函数。
self.b1.toggled.connect(lambda:self.btnstate(self.b1))
self.b2.toggled.connect(lambda:self.btnstate(self.b2))
btnstate() 函数检查按钮发出 toggled() 信号的状态。
if b.isChecked() == True:
print b.text()+" is selected"
else:
print b.text()+" is deselected"
QRadioButton 示例的完整代码如下 -
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Radiodemo(QWidget):
def __init__(self, parent = None):
super(Radiodemo, self).__init__(parent)
layout = QHBoxLayout()
self.b1 = QRadioButton("Button1")
self.b1.setChecked(True)
self.b1.toggled.connect(lambda:self.btnstate(self.b1))
layout.addWidget(self.b1)
self.b2 = QRadioButton("Button2")
self.b2.toggled.connect(lambda:self.btnstate(self.b2))
layout.addWidget(self.b2)
self.setLayout(layout)
self.setWindowTitle("RadioButton demo")
def btnstate(self,b):
if b.text() == "Button1":
if b.isChecked() == True:
print b.text()+" is selected"
else:
print b.text()+" is deselected"
if b.text() == "Button2":
if b.isChecked() == True:
print b.text()+" is selected"
else:
print b.text()+" is deselected"
def main():
app = QApplication(sys.argv)
ex = Radiodemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
上面的代码产生以下输出 -
Button1 is deselected
Button2 is selected
Button2 is deselected
Button1 is selected