Search code examples
c++qwidgetqt-quickqt5

Qt5 Using QWidget with QtQuick2


There are a few problems with the combination of Qt5 and QtQuick2. Whenever you would like to use some of the many QWidget based classes you first run across the following problem:

You should be using QApplication instead of Qt5's QGuiApplication. Well that can be easly changed, right?

So now I am using QApplication but whenever I try to use a QWidget based class my program either crashes or results in some nonsense error messages.

How should I use the old QWidgets with Qt5 then? I know that they are not the best solution with Qt5 but they are quite useful...

P.S. I am developing my app in Linux, for all platforms.
I am also using the auto-generated QtQuick2ApplicationViewer class to render out QtQuick 2.0 based applications.


Solution

  • In Qt 5.1 (and presumably from now on) you should use QWidget::createWindowContainer. Your application should be a QWidget based application and put the QML inside QWidgets. Putting QWidgets into a QML application is not supported.See this blog entry.

    If you have a form class and you want to put qml into the container widget.

    If you have this QML:

    import QtQuick 2.0
    
    Rectangle {
        property alias text: textItem.text
        width: 156
        height: 35
        Text {
            width: 150
            height: 20
            text: qsTr("Hello World")
            id: textItem
        }
    }
    

    In a file called myqml.qml, then put the path to it in to the qml prefix of a resource file.

    Then put in the form constructor:

    ui->setupUi(this); // as normal
    QQuickView* view = new QQuickView();
    QWidget* widget = QWidget::createWindowContainer(view, ui->container);
    view->setSource(QUrl("qrc:/qml/myqml.qml"));
    if(view->status()!=QQuickView::Ready)
        qDebug("can't initialise view");
    widget->setMinimumSize(500,100);
    QQuickItem* container = view->rootObject();
    

    Then when you want to interact with the QML:

    container->setProperty("text", "Hello alternate universe");