Andrej Fogelton
Andrej Fogelton

Reputation: 123

How to subclass QML Window?

I need to add some features in c++. But I struggle how to properly create my own QML window type. I have tried to subclass QQuickWindow and register my new type and use it in My QML project. But when starting it show error, that I can not set opacity

mywindow.h

#include <QQuickItem>
#include <QQuickWindow>
#include <QWindow>
#include <QApplication>
#include <QObject> 
class MyWindow : public QQuickWindow {
   Q_OBJECT
public:
   MyWindow(QQuickWindow *parent=nullptr); 
public slots:
   Q_INVOKABLE void mycppFeature();

mywindow.cpp

#include "reminderwindow.h"
MyWindow::MyWindow(QQuickWindow *parent):QQuickWindow(parent){
}

main.cpp

qmlRegisterType<MyWindow>("com.organization.my", 1, 0, "MyWindow");

SplashWindow.qml

import QtQuick 2.0
import QtQuick.Controls 2.5
import QtQuick.Window 2.15
import com.organization.my 1.0
MyWindow{
   opacity: 0.8

MyWindow is find but the error is "MyWindow.opacity" is not available in com.organizatino.my 1.0. I believe I do not know how to properly subclass the QML Window type. I use it besides the main ApplicationWindow When I use it without opacity, it works properly

Upvotes: 1

Views: 843

Answers (1)

David K. Hess
David K. Hess

Reputation: 17246

Add this to your MyWindow class declaration:

QML_FOREIGN(QQuickWindow)

The opacity property is declared on QWindow (inherited by QQuickWindow) like this:

    Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged REVISION(2, 1))

Meaning it was added in version 2.1 of the QtQuick.Window QML module.

The QML_FOREIGN documentation states:

Declares that any QML_ELEMENT, QML_NAMED_ELEMENT(), QML_ANONYMOUS, QML_INTERFACE, QML_UNCREATABLE(), QML_SINGLETON, QML_ADDED_IN_MINOR_VERSION(), QML_REMOVED_IN_MINOR_VERSION(), QML_ATTACHED(), or QML_EXTENDED() macros in the enclosing C++ type do not apply to the enclosing type but instead to FOREIGN_TYPE. The enclosing type still needs to be registered with the meta object system using a Q_GADGET or Q_OBJECT macro.

So that tells the QML machinery to not validate the version restrictions against your module but against the one that QQuickWindow is provided in.

More discussion in these bug reports similar to yours:

https://bugreports.qt.io/browse/QTBUG-91706

https://bugreports.qt.io/browse/QTBUG-72986

Upvotes: 0

Related Questions