Change the background color from slot PyQt… here is a solution to the problem.
Change the background color from slot PyQt
I want to be able to change the color of my app from the slot. For example, if a user enters the wrong data in the qlabel, the
entire QWidget turns red.
It’s easy to change the color in the code before the show()
method, as shown below
from PyQt5 import Qt
import sys
app = QtWidgets.QApplication(sys.argv)
window = QWidget()
p = window.palette()
p.setColor(window.backgroundRole(), QtCore.Qt.red)
window.setPalette(p)
window.show()
sys.exit(app.exec_())
But if I have this structure, I don’t know how to change the color in the slot :
class MyWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
uic.loadUi("file.ui", self)
self.sendButton.clicked.connect(self.change_color)
# what should be in change-color slot?
def change_color(self):
#.....?
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Should I somehow call QWidget’s pointer in the slot?
What is the way to implement the appropriate functionality here?
Solution
The instance of the class is the first parameter you pass to the method, in your case self
, so you must do the following:
def checks(self):
p = self.palette()
p.setColor(self.backgroundRole(), QtCore.Qt.red)
self.setPalette(p)