在pyqt中选择单选按钮时更改lineEdit的文本

sco*_*lta 2 python user-interface button radio pyqt4

radioButtons在使用qt设计器制作的表单中有两个,我现在用pyqt编程.我希望在选择lineEdit1时将文本更改为"radio 1",radioButton并在选择2时将其更改为"radio 2" radioButton.我该怎么做到这一点?

Gar*_*hes 9

这是一个简单的例子.每个QRadioButton都连接到它自己的功能.您可以将它们连接到同一个功能并管理通过它发生的事情,但我认为最好演示信号和插槽的工作原理.

有关更多信息,请查看PyQt4 文档以获取新样式信号和插槽.如果连接多个信号到同一插槽它有时可以使用.sender()的方法QObject,虽然在的情况下,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_())  
Run Code Online (Sandbox Code Playgroud)