Python working with Qt, event loop

倾然丶 夕夏残阳落幕 提交于 2019-12-11 20:21:38

问题


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)

回答1:


Qt Updates its Gui when it's Idle. To overcome this, you should use threading or yield your update function e.g. 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)  



回答2:


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)


来源:https://stackoverflow.com/questions/20716230/python-working-with-qt-event-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!