Complex 2D graphics in QtQuick via C++
-
Hi,
my goal is to implement custom QML element in C++. The purpose of this element is to draw rather complex 2D graphics (curves, polygons and polylines, text labels). And I also need to support mouse events handling (for example, editing polyline with mouse).In previous version of Qt I could reimplement method paint(QPainter *painter, ...) of QDeclarativeItem and use QPainter to perform graphics and text drawing, but in Qt 5 this approach is deprecated (see QQuickPaintedItem docs).
Currently I see two possibilites (described in Qt 5 docs):
- subclass QQuickItem
- write C++ QML plugin
Could you, please, advise me which of this two possibilities is more preferrable and suitable for my purposes (if any)?
Thanks in advance!
-
I think you'd better write your plugin.
How to create plugins for QML you can read "here":http://qt-project.org/doc/qt-5.0/qtqml/qtqml-modules-cppplugins.html. -
If you want to expose visual elements from C++ to QML you will end up subclassing QQuickItem anyway.
Whether you do that from your own application or from a plugin depends on the usecase, if you don't need the components in other application, then just registering the components from within your application is way easier to manage. A plugin is just overhead in most cases.
There are also other ways to get complex 2D graphics to QML:
You could implement a custom "QQuickImageProvider":http://qt-project.org/doc/qt-5.0/qtquick/qquickimageprovider.html and expose graphs this way.
Also you can draw directly in QML using the "QuickCanvas":http://qt-project.org/doc/qt-5.0/qtquick/quick-canvas.html.
-
[quote author="mutaphysis" date="1360702369"]If you want to expose visual elements from C++ to QML you will end up subclassing QQuickItem anyway.
There are also other ways to get complex 2D graphics to QML:
You could implement a custom "QQuickImageProvider"
Also you can draw directly in QML using the "QuickCanvas"[/quote]Thank you, mutaphysis! I'm trying to use QQuickItem - I've managed to draw lines and curves, but I can not figure out how can I draw a text with QQuickItem! Do you know?
I need to support editing graphics, so, I think, QQuickImageProvider is not appropriate. And I need to do graphics from C++, so Canvas is not appropriate too.
[quote author="Konstantin Podsvirov" date="1360680199"]I think you'd better write your plugin.
[/quote]Thank you, Konstantin! Does plugin provides a possibility to draw a text?
-
Hi,
See QQuickPaintedItem for this use case.
http://qt-project.org/doc/qt-5.0/qtquick/qquickpainteditem.htmlCheers,
Chris. -
Creating a plug-in (aka module) allows you to easily re-use your components.
The base class, use "QQuickPaintedItem":http://qt-project.org/doc/qt-5.0/qtquick/qquickpainteditem.html.
Override the "QQuickPaintedItem::paint":http://qt-project.org/doc/qt-5.0/qtquick/qquickpainteditem.html#paint.
You can draw text with the "painter->drawText":http://qt-project.org/doc/qt-5.0/qtgui/qpainter.html#drawText