Issue
I want to change the background color of my QLabel. On clicking the label, label connects to an event that sets the label color to Red
and loop runs for 3 second after 3 seconds and completion on loops the color of label should change to Yellow
This is the code:
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QApplication,QWidget,QDialog,QLabel
import sys
import time
def sleep4three():
for i in range(3):
print('inside the loop')
time.sleep(1)
class main(QDialog):
def __init__(self):
super(main,self).__init__()
loadUi('untitled.ui',self)
self.l.mousePressEvent = self.connect_
def connect_(self,event):
time.sleep(2)
ss = 'QLabel{background-color:red;}'
self.l.setStyleSheet(ss)
for i in range(3):
time.sleep(1)
self.l.setStyleSheet('QLabel{background-color:yellow;}')
if __name__ == '__main__':
app = QApplication(sys.argv)
main_ = main()
main_.show()
app.exec_()
But what's happening is the color of label l
never changes to Red
the execution directly jumps to the loop and i only see yellow colored l
Solution
Here is a tiny reproducible adaptation of your code that is also a demonstration of using QApplication.processEvents()
as was discussed in the comments. Hopefully this helps.
When this function is called it essentially pauses the execution of your code so that the GUI can process it's signals and updates and before resuming again.
from PyQt5.QtWidgets import *
import sys
import time
class main(QDialog):
def __init__(self):
super(main,self).__init__()
self.l = QLabel("label", self)
self.layout = QHBoxLayout(self)
self.layout.addWidget(self.l)
self.l.mousePressEvent = self.connect_
def connect_(self,event):
ss = 'QLabel{background-color:%s;}'
color = iter(["red", "green", "blue", "yellow", "white"])
self.l.setStyleSheet(ss % next(color))
QApplication.processEvents()
time.sleep(2)
for _ in range(3):
self.l.setStyleSheet(ss % next(color))
QApplication.processEvents()
time.sleep(1)
self.l.setStyleSheet(ss % next(color))
return super().mousePressEvent(event)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_ = main()
main_.show()
app.exec_()
Answered By - Alexander
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.