How to keep track of thread progress in Python without freezing the PyQt GUI?

后端 未结 5 1233
余生分开走
余生分开走 2020-12-12 20:07

Questions:

  1. What is the best practice for keeping track of a tread\'s progress without locking the GUI (\"Not Responding\")?
  2. Gene
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 20:34

    Native python queues won't work because you have to block on queue get(), which bungs up your UI.

    Qt essentially implements a queuing system on the inside for cross thread communication. Try this call from any thread to post a call to a slot.

    QtCore.QMetaObject.invokeMethod()

    It's clunky and is poorly documented, but it should do what you want even from from a non-Qt thread.

    You can also use event machinery for this. See QApplication (or QCoreApplication) for a method named something like "post".

    Edit: Here's a more complete example...

    I created my own class based on QWidget. It has a slot that accepts a string; I define it like this:

    @QtCore.pyqtSlot(str)
    def add_text(self, text):
       ...
    

    Later, I create an instance of this widget in the main GUI thread. From the main GUI thread or any other thread (knock on wood) I can call:

    QtCore.QMetaObject.invokeMethod(mywidget, "add_text", QtCore.Q_ARG(str,"hello world"))
    

    Clunky, but it gets you there.

    Dan.

提交回复
热议问题