Important: Please read the Qt Code of Conduct -

Getting QML-Item winId/Handle from C++ Code

  • What's the best approach of getting a QML handle (i.e. winId in QWidgets) of specific QML-Item from C++ code? in Qt Widgets I could simply retrieve the handle of any widget in order to draw with graphics api(In my case DirectX).
    Say we have this QML code:

    Window {
    id: rootWindow
    visible: true
    width: 640
    height: 480
    RendererForm {
    objectName: "rendererForm"
    id: rendererForm
    x: 120
    y: 35

    And I tried with C++ to do so:

    QObject * window = engine.rootObjects().first();
    QObject * rect = window->findChild<QObject*>("rendererForm");
    if (rect)
    QWindow * rectW = qobject_cast<QWindow *>(rect);
    if (rectW)
    qDebug() << "hmmmmmmmm";
    qDebug() << rectW->winId();

    Sadly this won't work. I'm kind of getting into QML lately, so if someone can enlighten me, that would be amazing. Thanks in advance!

  • I don't think there's any guarantee that anything except the top level Window will have anything like a native handle. Even with QtWidgets there's no guarantee that the individual widgets will all have native handles, unless you specifically poke them with WinId(). The composition modes and interactions between QML items don't map as well to native API definitions, so it makes even less sense. In-general, QML is pretty tied to OpenGL to trying to draw into the same Window with QML and DirectX will probably be difficult.

    Would it be possible to render offscreen using your native draw API's, and then use OpenGL texture interop so that your QML item just draws the result image as a texture on the QML side? I don't really have DirectX experience so my understanding of the interop is theoretical, but if you can render to a IDirect3DSurface9, says you can access it in OpenGL as a 2D texture.

  • @wrosecrans said in Getting QML-Item winId/Handle from C++ Code:

    unless you specifically poke them with WinId().

    Thanks for the answer! But how would I poke them with WinId()? I'm kind of new to QML, I guess if it will make things harder, I'll stick to QWidgets application and use QDeclarative to use QML in certain places.

    Drawing with DirectX using the WinId did work for me pretty well, but I'm kind of trying to force it to draw in the center of the Rectangle/Item so I can show some properties aside with the renderer form.

Log in to reply