0

I use PyQt to show the detection result. I have two threads one Ui_MainWindow ui and one QThread detect. I got the detect result(a float number) and want to use the ui.QProgressBar.setValue(result) in the detect.run but it would cause error sometimes.

The error is

QPainter::begin: A paint device can only be painted by one painter at a time.
QPainter::setCompositionMode: Painter not active

I searched this question and found I can not use setValue outside a GUI thread. And some answers say a signal and slot should be used to do this. Any one tell me how to write the code

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

You can not update the GUI from another thread, so there are several options like signals, QEvent, QMetaObject::invokeMethod() or QTimer::singleShot(0, ...) with functools.partial. I will use the last 2 methods:

  1. QMetaObject::invokeMethod()
QtCore.QMetaObject.invokeMethod(
    ui.QProgressBar, "setValue", QtCore.Qt.QueuedConnection, QtCore.Q_ARG(result)
)
  1. QTimer::singleShot(0, ...) with functools.partial:
from functools import partial

# ...

wrapper = partial(ui.QProgressBar.setValue, result)
QtCore.QTimer.singleShot(0, wrapper)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241