Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending QML ApplicationWindow in C++

Tags:

c++

qt

qt-quick

qml

How can you properly extend the QML ApplicationWindow type? According to the documentation, ApplicationWindow instantiates a QQuickWindow. So I tried sub classing from QQuickWindow and exposing the type to QML as MyWindow. The problem is that MyWindow doesn't actually extend the QML type ApplicationWindow, so you don't get all the properties like menuBar and toolBar. How can I extend ApplicationWindow in C++ and expose it to QML? Here is what I'm currently doing:

class MyQuickWindow : public QQuickWindow
{
    //...irrelevant additions
}


int main()
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<MyQuickWindow>("MyExtensions", 1, 0, "MyApplicationWindow");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    return app.exec();
}

Here is the QML file:

import QtQuick 2.0
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
import MyExtensions 1.0

MyApplicationWindow {
    width: 800
    height: 600
    visible: true

    menuBar: MenuBar {    // ERROR: menuBar is not a property
        Menu {
            title: "File"
            MenuItem { text: "New" }
            MenuItem { text: "Open" }
        }
    }
}

Note that I need to have my own additions in C++ to the QQuickWindow for other reasons.

like image 432
Dan Watkins Avatar asked Nov 09 '22 22:11

Dan Watkins


1 Answers

It seems like the job for qmlRegisterType. And it is a bit hard to say if you miss something with your C++ part but registering the type should help. That is for exposing the type itself and should enable the derived QQuickWindow functionality (derived from ApplicationWindow actually). But for what you are adding you need to deal with Q_PROPERTY and Q_INVOKABLE (which is for functions) mechanism. See the whole bunch of Q_* QObject macro.

And if that was not enough then there is an example for such inheritance.

Correction: the author is dealing with QML-made type but he can still try to mimic the type on his own. The path to ApplicationWindow.qml source code is: C:\Qt\5.3\Src\qtquickcontrols\src\controls where C:\Qt\5.3\ is the root for selected Qt version.I would attempt that and that is feasible unless we want to find out about explicit QML inheritance. That file can also be found at Qt source code repository.

like image 72
Alexander V Avatar answered Nov 14 '22 23:11

Alexander V