Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Instantiating QML Dialog from c++, "cannot find any window to open popup in"



  • [Qt 5.15.2, Win10, MinGW64]
    I am trying to open up a Popup or a Dialog from the c++ side.
    I get this error message:

    boxComp.errorString():  ""
    boxComp.errors(): ()
    qrc:/UserInteractionBox.qml:4:1: QML UserInteractionBox: cannot find any window to open popup in.
    

    My code does work, if I use Window {...} instead of Popup […} or Dialog{…}, but I want to use dynamic instantiation in several contexts and I need the functionality of the QQuick items.

    From c++, I instantiate it this way:

    void createBox(QQuickWindow* window) {
            QQmlComponent boxComp( m_engine, QUrl( "qrc:/UserInteractionBox.qml" ) );
            qDebug()<<"boxComp.errorString(): "<<boxComp.errorString();
            qDebug()<<"boxComp.errors():"<<boxComp.errors();
    
            boxComp.setParent(window);
            auto obj = boxComp.create(m_engine->rootContext());
    }
    

    I call this with

    auto box = new UserInteractionBox(&engine,"test", "test","test");
    box->createBox(m_view);
    
    

    With m_view being a controller member that holds the view used to load main.qml

    m_view = new QQuickView(&engine, nullptr);
    

    This is my Dialog, UserInteractionBox.qml:

    import QtQuick 2.0
    import QtQuick.Controls 2.15
    
    Dialog {
       id: userInteractionBox
        title: "some title"
        property string text: "initialText"
        Component.onCompleted: open()
    
    }
    

    So:
    How can I provide a valid Window to open a new item in?



  • Solved. The error message, speaking about a "window", is a bit misleading, as we need to set not the window itself, but the window's contentItem() as a parent.

    For posterity, my working code:

            QQuickWindow *mainWindow = qobject_cast<QQuickWindow*>(m_engine->rootObjects().value(0));
            QQmlComponent boxComp( m_engine, QUrl( "qrc:/UserInteractionBox.qml" ) );
            QVariantMap initialProperties;
            initialProperties["parent"] = QVariant::fromValue(mainWindow->contentItem());
            initialProperties["title"] = m_title;
            initialProperties["text"] = m_text;
            QQmlContext *ctxt = m_view->rootContext();
            auto obj = boxComp.createWithInitialProperties(initialProperties,ctxt);
            QMetaObject::invokeMethod(obj, "open");
    

    As for the Dialog, my starting point is simply:

    import QtQuick 2.0
    import QtQuick.Controls 2.15
    
    Dialog {
        id: userInteractionBox
        property string text: ""
        
        TextArea {
            anchors.fill: parent
            text: userInteractionBox.text
        }
    }
    

Log in to reply