问题
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