iBug
iBug

Reputation: 37317

PyQt5 UI stuck at long operation

I'm creating a game with some AI that may take some time. The problem is even if I call relevant methods to update the UI before running the AI function, the UI is not visually updated.

Some example code looks like this

    def onClickBoard(self, e):
        x, y = toBoardGrid(e.x(), e.y())
        self.game.move(x, y)
        self.update_board()

        print("before AI")
        # This line takes a few seconds
        ai_move = self.ai.get_best_move(self.game)
        print("after AI")
        self.game.move(ai_move[0], ai_move[1])
        self.update_board()

Where self.update_board is a method that updates a QWidget and it's very fast. This onClickBoard method is assigned to the widget's mouseReleaseEvent.

    self.board.mouseReleaseEvent = self.onClickBoard

When running the game, I can see before AI printed to the terminal but the visual window doesn't change. I see the window updates only once, after the AI commits its move.

Is there a way to make the board update once before the slow function call and another once after it?

Upvotes: 1

Views: 592

Answers (1)

titusjan
titusjan

Reputation: 5546

Yes, you can force Qt to process all pending events, and thus update the GUI, with the QApplication::processEvents() method. Add the following line just before the slow function call:

QtWidgets.QApplication.instance().processEvents()

Upvotes: 1

Related Questions