Search code examples
pythonpyside2qlineedit

QLineEdit readOnly disables clear button as well


Essentially this post describes the problem however the answers are for c++ and I'd like to know if there is a way to do this in python.

Turning a lineedit into readOnly mode also disables the clearButton and I wondered if it is possible to keep the clearButton functionality active. Is it possible to extend the action that gets triggered on a clearButton click with some custom functionality (if it is possible to access the clearbutton at all)?


Solution

  • When readOnly is set to QLineEdit it disables QToolButton (clear button), so the solution is to enable it, and for this you must obtain the button using the findChild() method:

    from PySide2 import QtWidgets
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        le = QtWidgets.QLineEdit(
            text="Stack Overflow", readOnly=True, clearButtonEnabled=True
        )
        le.findChild(QtWidgets.QToolButton).setEnabled(True)
        le.show()
        sys.exit(app.exec_())