I need to add a button to QLineEdit, set it checkable and change icon according to checked/unchecked state. I do this that way:
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(os.path.join("Images", "L.png")), QtGui.QIcon.Normal, QtGui.QIcon.On)
icon.addPixmap(QtGui.QPixmap(os.path.join("Images", "Home.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
searchActionBttn = QtWidgets.QAction("None", self.searchIn)
searchActionBttn.triggered.connect(lambda: print(searchActionBttn.isChecked()))
searchActionBttn.setCheckable(True)
searchActionBttn.setIcon(icon)
self.searchIn.addAction(searchActionBttn, QtWidgets.QLineEdit.LeadingPosition)
But icon didn't change when I click on it.
The problem is caused because the QToolButton associated with the QAction has its custom paintEvent method so it does not take into account the state of the checkbox
(emphasis mine)
As you can see, the state only changes while the button is pressed, so the option of using a QAction should be discarded.
Another option is to set the QToolButton directly through a layout