我有一个想要在其中执行以下操作的应用程序:
我想在单击QPushButton时开始整个过程。仅当步骤1.)完全终止时才需要开始步骤2.)。我不知道优化过程要花多长时间,我只能使用QTimer.sleep()。
我已经通过以下方式解决了这个问题:
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5 import QtWidgets
import sys
class MyForm():
def __init__(self):
self.ui = QDialog()
self.button = QtWidgets.QPushButton(self.ui)
self.button.clicked.connect(self.start_timer)
self.waiting_interval = 10000
self.ui.show()
def start_timer(self):
self.optimize()
self.counter = 0
self.timer = QTimer()
self.timer.timeout.connect(self.tick)
self.timer.setSingleShot(True)
self.timer.start(self.waiting_interval)
def tick(self):
self.timer = QTimer()
if self.counter == 9:
self.timer.timeout.connect(self.start_timer)
else:
self.measure_property()
self.timer.timeout.connect(self.tick)
self.timer.setSingleShot(True)
self.timer.start(self.waiting_interval)
self.counter += 1
def optimize(self):
pass
def measure_property(self):
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
w=MyForm()
app.exec_()
它会产生我想要的结果,但我正在寻找一种更智能的方式来执行此操作,也许使用信号和插槽。任何帮助将不胜感激!
答案 0 :(得分:1)
耗时较长的任务很繁重,并且倾向于冻结GUI,给用户带来不好的体验,在这些情况下,这些任务必须在另一个线程中执行:
import sys
from PyQt5 import QtCore, QtWidgets
class ProcessThread(QtCore.QThread):
def run(self):
while True:
self.optimize()
for _ in range(3):
QtCore.QThread.sleep(60)
self.measure_property()
def optimize(self):
print("optimize")
def measure_property(self):
print("measure_property")
class MyForm():
def __init__(self):
self.ui = QtWidgets.QDialog()
self.thread = ProcessThread(self.ui)
self.button = QtWidgets.QPushButton("Press me")
self.button.clicked.connect(self.thread.start)
self.waiting_interval = 10000
lay = QtWidgets.QVBoxLayout(self.ui)
lay.addWidget(self.button)
self.ui.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w=MyForm()
sys.exit(app.exec_())