Sync QQuickPaintedItem and QML painting
-
Hi everyone,
i want to sync QQuickPaintedItem and QML painting. To do this, I've QQuickPaintedItem which is drawing a rectangle at a certain position, signaling this position to QML and drawing also there a rectangle.
QQuickPaintedItem
#include "painter.h" #include <QPainter> #include <QTimer> Painter::Painter(QQuickPaintedItem* parent) : pi_(0.0) { QObject::connect(&timer_, &QTimer::timeout, this, &Painter::onTimer); timer_.start(30); } void Painter::onTimer() { pnt_.setX(300 + sin(pi_) * 150.0); pnt_.setY(150); pi_ += 0.05; update(); } QPointF Painter::pntPosition() const { return pnt_; } void Painter::paint(QPainter* painter) { painter->setBrush(QBrush(QColor(255, 0, 0))); QRectF rect(pnt_.x() - 2, pnt_.y() - 2, 4, 4); painter->drawRect(rect); emit pntPositionChanged(); }
QML
import QtQuick import TestPainter 1.0 Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Painter { id: painter width: parent.width height: parent.height Rectangle { x: painter.pntPosition.x - 2 y: painter.pntPosition.y - 2 - 20 width: 4 height: 4 color: "#000000" } } }
The result of this code is, that the QML rectangle is lagging:
How can I sync the draw correctly?
Thanks a lot!
Best Mario -
Based on a quick read of the documentation, I don't think that this strategy will work.
https://doc.qt.io/qt-6/qquickpainteditem.html#paint
Note: The QML Scene Graph uses two separate threads, the main thread does things such as processing events or updating animations while a second thread does the actual issuing of graphics resource updates and the recording of draw calls. As a consequence, paint() is not called from the main GUI thread but from the GL enabled renderer thread. At the moment paint() is called, the GUI thread is blocked and this is therefore thread-safe.
Warning: Extreme caution must be used when creating QObjects, emitting signals, starting timers and similar inside this function as these will have affinity to the rendering thread.