pythonpyside2qradiobutton

How to make QRadioButton clickable area the whole button instead of just on the text


I'm using PySide2, within maya 2018, if that matters. A QRadioButton will respond only if clicked in the area of the text, even if the button's rectangle is larger. A QPushButton can be clicked anywhere in its rectangle and it will respond. Can I get the QRadioButton to act like the QPushButton in this respect?


Solution

  • Every button that inherits from QAbstractButton like QPushButton and QRadioButton must implement the hitButton() method that indicates if the position changes the state of the button. So in the case of QPushButton it takes all its geometry as reference, instead QRadioButton takes as reference the text + the radius. The solution is to override that method so that it has the desired behavior:

    import os
    import sys
    
    from PySide2 import QtCore, QtWidgets
    
    
    class CustomRadioButton(QtWidgets.QRadioButton):
        def hitButton(self, pos):
            return self.rect().contains(pos)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
    
        w = QtWidgets.QWidget()
        lay = QtWidgets.QVBoxLayout(w)
        for i in range(4):
            btn = QtWidgets.QRadioButton(f"QRadioButton-{i}")
            lay.addWidget(btn)
        for j in range(4):
            btn = CustomRadioButton(f"CustomRadioButton-{i}")
            lay.addWidget(btn)
    
        w.resize(640, 480)
        w.show()
        sys.exit(app.exec_())