Python:在指令后更新GUI

时间:2018-06-27 17:21:13

标签: python pyside sleep

我设计了一个程序来解决Rubik的多维数据集,现在我正在使用PySide为其构建GUI。我的程序生成了求解该多维数据集所需的一系列动作,然后逐个执行它们。我希望我的程序在每次移动之间的短时间内显示多维数据集的状态。

当前,我正在尝试使用时间模块使程序在执行两次移动之间等待。基本上是这样的:

for move in algorithm:
    executeMove()
    updateDisplay()
    time.sleep(0.1)

我认为这种方法可以正常工作。但是,当我运行该应用程序时,它看起来像在每个睡眠调用的总时间中处于睡眠状态,然后显示了算法的最终结果。理想情况下,我想让它显示移动,睡眠0.1,显示移动,睡眠0.1等。

睡眠功能是否很适合我要尝试的行为类型?我应该使用完全不同的东西吗?谢谢您的建议。

1 个答案:

答案 0 :(得分:0)

看到更多代码是一件好事,但是看起来您可能正在阻塞Qt主线程。要完成您想做的事情,您将需要使用多线程并使用pyQtSignal来更新UI。这是一个(可能是错误的)模板

class MainWindow(QtWidgets.QMainWindow):
    updateSignal = QtCore.pyqtSignal()
    def __init__(self, algorithm):
        super(MainWindow, self).__init__()
        self.algorithm = algorithm
        self.updateSignal.connect(self.updateDisplay)
        self.loopThread = None
        self.startMonitoring()
    def startMonitoring(self):
        self.loopThread = MonitorLoop(self.updateSignal.emit, self.algorithm)
        self.loopThread.start()
    def updateDisplay(self):
        """ Update the UI here"""
        pass


class MonitorLoop(QtCore.QThread):
    def __init__(self, signal, algorithm):
        super(MonitorLoop, self).__init__()
        self.signal = signal # needs to be a pyQtSignal if it will update the UI
        self.algorithm = algorithm
    def run(self):
        for move in self.algorithm:
            executeMove()
            self.signal()
            time.sleep(0.1)

如果您使用的是Qt 4,则需要用QtGui代替QWidgets。当然,我实际上并不知道algorithm是什么,因此您的实现需要适应这一点。

相关问题