QQuickPaintedItem mappings created in c++
-
Hello everyone, I want to add a QQuickPaintedItem that is created by another class to the qml display. Please tell me how I can do this?
int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); QQmlApplicationEngine engine; gst_init (nullptr, nullptr); QScopedPointer<VideoItem> v(new VideoItem("video_gsp1TV.conf")); QQuickPaintedItem* graphItem = v->getGraphicsItem(); engine.rootContext()->setContextProperty("graph", QVariant::fromValue(graphItem)); const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); }
and class GraphItem
class GraphItem : public QQuickPaintedItem { Q_OBJECT QML_ELEMENT public: GraphItem(QQuickPaintedItem *parent = nullptr) : QQuickPaintedItem(parent) { // connect(item, &VideoItem::newFrame, // this, &GraphItem::onNewFrame); } QRectF boundingRect() const override{ return _rect; } void paint(QPainter *painter) override { qDebug() << "1111"; painter->drawImage(_rect, _image); } public slots: void onNewFrame(QImage image){ _image = image; // if(this->scene()!=Q_NULLPTR)this->scene()->update(); update(_rect.toRect()); } protected: void itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &value) override { if(change == ItemSceneChange ){ _rect = QRectF(0, 0, width(), height()); } QQuickPaintedItem::itemChange(change, value); } private: QImage _image; QRectF _rect; };
-
@Idodoqdo
setContextProperty
is usually used to inject backend C++ objects such as models or APIs into the QML layer. (Also, people will tell you to preferqmlRegisterSingletonInstance
oversetContextProperty
these days, but that is not too important here.)The cleanest way to expose a
QQuickPaintedObject
to QML that I am aware of is to useqmlRegisterType<type>
, which makes your C++ object available as a QML component. For example, if you register your object as:qmlRegisterType<GraphItem>("MyTypes", 1, 0, "GraphItem");
In your QML you can do things like:
import MyTypes 1.0 Item { GraphItem { ... } ...
or you could use
createComponent
to instantiate it dynamically.However this approach relies on the QML engine being able to instantiate the object. It looks like you have another object that is responsible for constructing your
GraphItem
s.I wonder if what you are trying to do is closer to the scenario asked about in this StackOverflow question: https://stackoverflow.com/questions/45839728/how-to-add-a-dynamically-created-qquickitem-to-my-applications-main-qml-or-the.