python - re-dimension element with a random number

2

I want to re-dimension the frame that I create, the idea is to take a random number to pass it as value height() , this must be done in a certain cycle in this case 100 times with a value update time each second time.sleep(1) , this should update the frame size graphically but it does not.

Here I leave my code I hope you can support me:

import sys
import random
import time
from PyQt5.QtWidgets import QMainWindow, QApplication, QFrame
from PyQt5 import uic


class Principal(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)


        frame = QFrame(self)
        frame.setGeometry(200,200,10,50)
        frame.setStyleSheet('background-color:lightblue')

        n=0
        while n<100:
            s = random.randint(0,100)
            frame.resize(10,s)
            time.sleep(1)
            print(s)
            n+=1


app = QApplication([])
principal = Principal()
principal.resize(600,400)
principal.show()
app.exec_()
    
asked by Revsky01 18.03.2018 в 05:26
source

1 answer

1

sleep() is a blocking task and these types of tasks should not be executed in the main thread called the GUI thread since they block other tasks that you have to do, such as displaying widgets, redrawing, receiving events from the mouse, etc.

The GUIs offer alternatives for this type of tasks without needing to be blockers, in the case of Qt, and therefore PyQt, QTimer should be used:

import sys
import random

from PyQt5.QtWidgets import QMainWindow, QApplication, QFrame
from PyQt5.QtCore import QTimer

class Principal(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.frame = QFrame(self)
        self.frame.setGeometry(200,200,10,50)
        self.frame.setStyleSheet('background-color:lightblue')

        self.timer = QTimer(self)    
        self.n = 0
        self.timer.timeout.connect(self.on_timeout)
        self.timer.start(1000)

    def on_timeout(self):
        if self.n < 100:
            s = random.randint(0,100)
            self.frame.resize(10,s)
            print(s)
            self.n += 1
        else:
            self.timer.stop()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    principal = Principal()
    principal.resize(600,400)
    principal.show()
    sys.exit(app.exec_())
    
answered by 18.03.2018 / 08:34
source