简体   繁体   中英

Python working with Qt, event loop

I have a problem with event loop. To understand, i want to update Label/textBrowser/lineEdit text during some loop while Stop button isn't pushed.

def __init__(self):
    QtGui.QMainWindow.__init__(self)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.ui.btnStart.clicked.connect(self.btnStart_Clicked)
    self.ui.btnStop.clicked.connect(self.btnStop_Clicked)
    self.startTime = dt.datetime(2013, 1, 1, 0, 0, 0)
    self.nowTime = dt.datetime(2013, 1, 1, 0, 0, 0)
    self.ui.lineStart.setText(self.startTime.strftime("%Y-%m-%d %H:%M"))
    self.ui.lineNow.setText(self.nowTime.strftime("%Y-%m-%d %H:%M"))
    self.ui.textBrowser.setText(self.nowTime.strftime("%Y-%m-%d %H:%M"))



def btnStart_Clicked(self):
    print(12)
    while (not self.btnStop_Clicked()):
        print(23)
        self.nowTime += dt.timedelta(minutes = 25)
        self.ui.textBrowser.setText(self.nowTime.strftime("%Y-%m-%d %H:%M"))
        time.sleep(2)

Qt Updates its Gui when it's Idle. To overcome this, you should use threading or yield your update function eg by using a timer to update instead. Below is some code I use to reschedule an update each 100ms. The use case is similar to yours.

    self.timer = QtCore.QTimer(self.wid)
    self.timer.timeout.connect(self.UpdateTab)
    self.timer.start(100)  

To request an immediate update, use processEvents :

while (not self.btnStop_Clicked()):
    self.nowTime += dt.timedelta(minutes = 25)
    self.ui.textBrowser.setText(self.nowTime.strftime("%Y-%m-%d %H:%M"))
    QtGui.qApp.processEvents()
    time.sleep(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM