Files
templates/python/set_devices/qt_ports/plot_layers.py

47 lines
1.7 KiB
Python

"""Queued redraws and cached static layers for Qt plots (Qt 5/6)."""
try:
from PySide6.QtCore import QTimer, Qt
from PySide6.QtGui import QPixmap, QPainter
except ImportError:
from PySide2.QtCore import QTimer, Qt
from PySide2.QtGui import QPixmap, QPainter
class PlotLayers:
def init_plot_layers(self):
self._static_revision = 0
self._static_plot_layer = None
self._redraw_timer = QTimer(self)
self._redraw_timer.setSingleShot(True)
self._redraw_timer.timeout.connect(self._flush_plot_update)
def update(self, *args):
if not hasattr(self, '_redraw_timer'):
return super().update(*args)
self._static_revision += 1
self.update_overlay()
def update_overlay(self):
if not hasattr(self, '_redraw_timer'):
return super().update()
if not self._redraw_timer.isActive():
self._redraw_timer.start(0)
def _flush_plot_update(self):
super().update()
def paint_static_layer(self, painter, draw):
ratio = self.devicePixelRatioF()
key = (self._static_revision, self.width(), self.height(), ratio,
tuple(self.plot_rect().getRect()))
if self._static_plot_layer is None or self._static_plot_layer[0] != key:
image = QPixmap(round(self.width()*ratio), round(self.height()*ratio))
image.setDevicePixelRatio(ratio)
image.fill(Qt.GlobalColor.transparent)
layer = QPainter(image)
try:
draw(layer)
finally:
layer.end()
self._static_plot_layer = key, image
painter.drawPixmap(0, 0, self._static_plot_layer[1])