Как присвоить значение радиокнопке в pyqt?
Я хочу присвоить значение радиокнопке, когда оно проверено.
def radiobutton8(self):
if self.radioButton_8.isChecked():
self.radioButton_8 = 02
Однако это не может работать. Любое решение?
ОБНОВЛЕНИЕ: мой код был отредактирован, чтобы быть:
class MyRadioButton(QtGui.QRadioButton):
def __init__(self):
super(MyRadioButton, self).__init__()
self.value = None
def SetValue(self, val):
self.value = val
def GetValue(self):
return self.value
class UserTool(QtGui.QDialog):
def setup(self, Dialog):
...
self.radioButton_8.toggled.connect(self.radiobutton8)
def retranslateUi(self, Dialog):
...
self.radioButton_8 = MyRadioButton()
self.radioButton_8.setText(_translate("Dialog", "A1", None))
def radiobutton8(self):
if self.radioButton_8.isChecked():
value = self.radioButton_8.setValue("02")
self.lcdNumber.display(value)
Тем не менее, мой исходный текст "А1" для переключателя теперь отсутствует, и мой номер по-прежнему не отображается на ЖК-дисплее при проверке. Есть идеи почему?
ОБНОВЛЕНИЕ: я отредактировал мой код, чтобы он был примерно таким:
class MyRadioButton(QtGui.QRadioButton):
def __init__(self):
super(MyRadioButton, self).__init__()
self.value = None
def SetValue(self, val):
self.value = val
def GetValue(self):
return self.value
class UserTool(QtGui.QDialog):
def setup(self, Dialog):
...
self.lcdNumber = QtGui.QLCDNumber(Dialog)
self.lcdNumber.setGeometry(QtCore.QRect(590, 10, 71, 23))
self.lcdNumber.setFrameShadow(QtGui.QFrame.Raised)
self.lcdNumber.setObjectName(_fromUtf8("lcdNumber"))
self.lcdNumber.setStyleSheet("* {background-color: black; color: white;}")
self.lcdNumber.display('00')
self.radioButton_8 = QtGui.QRadioButton(Dialog)
self.radioButton_8.setGeometry(QtCore.QRect(460, 10, 82, 17))
self.radioButton_8.setChecked(False)
self.radioButton_8.setAutoExclusive(False)
self.radioButton_8.setObjectName(_fromUtf8("radioButton_8"))
self.radioButton_8 = MyRadioButton()
self.radioButton_8.setText("A1")
self.radioButton_8.setValue(02)
self.radioButton_8.toggled.connect(self.showValueFromRadioButtonToLCDNumber)
def showValueFromRadioButtonToLCDNumber(self):
value = self.radioButton_8.GetValue()
if self.radioButton_8.isChecked():
self.lcdNumber.display(value)
И тогда теперь у меня есть эта ошибка:
Traceback (most recent call last):
File "C:/Users/Vivien Phua/Documents/Python Scripts/Rs232.py", line 303, in handleOpenWidget
self.popup = UserTool()
File "C:/Users/Vivien Phua/Documents/Python Scripts/Rs232.py", line 39, in __init__
self.setup(self)
File "C:/Users/Vivien Phua/Documents/Python Scripts/Rs232.py", line 153, in setup
self.radioButton_8.setValue(02)
AttributeError: 'MyRadioButton' object has no attribute 'setValue'
Я также попробовал код, который вы мне дали, и такой ошибки нет, но на ЖК-дисплее в вашем коде не отображается значение 02.
1 ответ
Вы имеете в виду текстовое значение рядом с radioButton? Если это так, вот решение:
def radiobutton8(self):
if self.radioButton_8.isChecked():
self.radioButton_8.setText("02")
EDIT1: RadioButton не имеет поля значения, как вам нужно. Однако вы можете написать свой собственный класс radiobButton, который наследует оригинальный QRadioButton, и добавить это поле. Пример:
class MyRadioButton(QtGui.QRadioButton):
def __init__(self):
super(MyRadioButton, self).__init__()
self.value = None
def SetValue(self, val):
self.value = val
def GetValue(self):
return self.value
и используйте это так:
self.radioButton_8 = MyRadioButton()
self.radioButton_8.setText("some text")
...
def radiobutton8(self):
if self.radioButton_8.isChecked():
self.radioButton_8.SetValue("02")# or .SetValue(2) if you want it to be integer
EDIT2
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
class MyRadioButton(QtGui.QRadioButton):
def __init__(self):
super(MyRadioButton, self).__init__()
self.value = None
def SetValue(self, val):
self.value = val
def GetValue(self):
return self.value
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
self.layout = QtGui.QVBoxLayout(self)
self.pushButton_7 = QtGui.QPushButton("if RB is checked, show it's value to LCD")
self.pushButton_7.setGeometry(QtCore.QRect(220, 650, 75, 23))
self.pushButton_7.clicked.connect(self.showValueFromRadioButtonToLCDNumber)
self.radioButton = MyRadioButton()
self.radioButton.setText("some text")
self.radioButton.SetValue("02")# somewhere in code first set value to radio button
self.lcdNumber = QtGui.QLCDNumber()
self.layout.addWidget(self.pushButton_7)
self.layout.addWidget(self.radioButton)
self.layout.addWidget(self.lcdNumber)
def showValueFromRadioButtonToLCDNumber(self):
value = self.radioButton.GetValue()
if self.radioButton.isChecked():
self.lcdNumber.display(value)
if __name__ == '__main__':
app = QtGui.QApplication([])
w = Widget()
w.show()
sys.exit(app.exec_())