在PyQt中选择单选按钮时改变lineEdit的文本
我在用qt设计器做一个表单,里面有两个radioButtons
(单选按钮),现在我在用pyqt编程。我想要实现这样的功能:当选择第一个radioButton
时,lineEdit
的文本变成“radio 1”;当选择第二个radioButton
时,lineEdit
的文本变成“radio 2”。我该怎么做呢?
1 个回答
10
这是一个简单的例子。每个 QRadioButton
(单选按钮)都连接到它自己的功能。你也可以把它们都连接到同一个功能,然后通过这个功能来管理发生的事情,但我觉得最好还是演示一下信号和槽是怎么工作的。
想了解更多信息,可以查看 PyQt4 的 新风格信号和槽的文档。如果把多个信号连接到同一个槽,有时候使用 .sender()
方法会很有用,虽然在 QRadioButton
的情况下,直接检查你想要的按钮的 .isChecked() 方法可能更简单。
import sys
from PyQt4.QtGui import QApplication, QWidget, QVBoxLayout, \
QLineEdit, QRadioButton
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.widget_layout = QVBoxLayout()
self.radio1 = QRadioButton('Radio 1')
self.radio2 = QRadioButton('Radio 2')
self.line_edit = QLineEdit()
self.radio1.toggled.connect(self.radio1_clicked)
self.radio2.toggled.connect(self.radio2_clicked)
self.widget_layout.addWidget(self.radio1)
self.widget_layout.addWidget(self.radio2)
self.widget_layout.addWidget(self.line_edit)
self.setLayout(self.widget_layout)
def radio1_clicked(self, enabled):
if enabled:
self.line_edit.setText('Radio 1')
def radio2_clicked(self, enabled):
if enabled:
self.line_edit.setText('Radio 2')
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = Widget()
widget.show()
sys.exit(app.exec_())