Как вставить интерактивную иконку вместо кнопки radio?
Мне нужно заменить обычную кнопку QRadioButton на иконку.
self.radioButton = QRadioButton(self.centralwidget)
self.radioButton.setObjectName(u"radioButton")
self.radioButton.setGeometry(QRect(50, 30, 111, 101))
icon = QIcon()
icon.addFile(u"3.svg", QSize(), QIcon.Normal, QIcon.Off)
icon.addFile(u"2.svg", QSize(), QIcon.Normal, QIcon.On)
self.radioButton.setIcon(icon)
Код был сгенерирован программой QT Designer
Но я не совсем понимаю, почему иконка не меняется после нажатия на радио и как вообще скрыть дефолтную иконку radio.
чтобы потом заменить ее иконкой.
Ответы (1 шт):
Автор решения: S. Nick
→ Ссылка
В общем случае надо переопределять метод paintEvent
в классе наследованном от QRadioButton.
Как вариант:
import sys
from PyQt5.QtWidgets import (QRadioButton, QHBoxLayout, QButtonGroup,
QApplication, QWidget)
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import QSize, Qt
from PyQt5 import QtCore, QtGui, QtWidgets
class RadioButton(QRadioButton):
def __init__(self, parent=None):
super(RadioButton, self).__init__(parent)
self.pixmap = QPixmap("LightOff.png")
self.pixmap_pressed = QPixmap("lightOn.png")
self.setText('rb0')
def paintEvent(self, event):
if self.isChecked():
pix = self.pixmap_pressed
else:
pix = self.pixmap
painter = QtGui.QPainter(self)
painter.drawPixmap(event.rect(), pix)
def sizeHint(self):
return QtCore.QSize(30, 30)
class Window(QWidget):
def __init__(self):
super().__init__()
self._dictRB = {
'rb0': False,
'rb1': False,
'rb2': False,
'rb3': False,
}
self.main_layout = QHBoxLayout(self)
self.buttonGroup = QButtonGroup()
self.attr_layout = QHBoxLayout()
self.main_layout.addLayout(self.attr_layout)
self.rb0 = RadioButton() #QRadioButton() # 'rb0'
self.attr_layout.addWidget(self.rb0)
self.buttonGroup.addButton(self.rb0)
self.rb1 = QRadioButton('rb1')
self.attr_layout.addWidget(self.rb1)
self.buttonGroup.addButton(self.rb1)
self.rb2 = QRadioButton('rb2')
self.attr_layout.addWidget(self.rb2)
self.buttonGroup.addButton(self.rb2)
self.rb3 = QRadioButton('rb3')
self.buttonGroup.addButton(self.rb3)
self.buttonGroup.buttonClicked.connect(self.check_button)
def check_button(self, radioButton):
if self._dictRB[radioButton.text()]:
self._dictRB[radioButton.text()] = False
self._dictRB['rb3'] = True
self.rb3.setChecked(True)
else:
for b in self._dictRB:
self._dictRB[b] = False
self._dictRB[radioButton.text()] = True
print("Нажата кнопка -> `{} - {}`".format(radioButton.text(), radioButton.isChecked()))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())


