Create attached properties in c++
-
hello i am trying to create custom attached properties in c++ but it dosnt seem to work, here is the code:
// sidemenu.h #include <QtCore> #include <qqml.h> #include <QtQuick/QQuickItem> class SideMenuAttached : public QObject { Q_OBJECT Q_PROPERTY(bool isCurrenPage READ isCurrenPage NOTIFY isCurrenPageChanged) QML_ANONYMOUS public: using QObject::QObject; bool isCurrenPage() const; void setIsCurrenPage(bool newIsCurrenPage); signals: void isCurrenPageChanged(); private: bool m_isCurrenPage = false; }; class SideMenu : public QQuickItem { Q_OBJECT Q_PROPERTY(int currentPage READ currentPage WRITE setCurrentPage NOTIFY currentPageChanged) QML_ELEMENT QML_ATTACHED(SideMenuAttached) public: explicit SideMenu(QQuickItem *parent = nullptr); int currentPage() const; void setCurrentPage(int newCurrentPage); static SideMenuAttached *qmlAttachedProperties(QObject *); signals: void currentPageChanged(); private: int m_currentPage; };
//sidemenu.cpp #include "sidemenu.h" bool SideMenuAttached::isCurrenPage() const { return m_isCurrenPage; } void SideMenuAttached::setIsCurrenPage(bool newIsCurrenPage) { if (m_isCurrenPage == newIsCurrenPage) return; m_isCurrenPage = newIsCurrenPage; emit isCurrenPageChanged(); } SideMenu::SideMenu(QQuickItem *parent) : QQuickItem(parent) { } int SideMenu::currentPage() const { return m_currentPage; } void SideMenu::setCurrentPage(int newCurrentPage) { if (m_currentPage == newCurrentPage) return; m_currentPage = newCurrentPage; emit currentPageChanged(); } SideMenuAttached *SideMenu::qmlAttachedProperties(QObject *object) { return new SideMenuAttached(object); }
// main.qml import QtQuick import components 1.0 as T Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Item{ anchors.fill: parent; T.SideMenu{ currentPage: 0; anchors.fill: parent; Rectangle{id: a; anchors.fill: parent; color: "grey" Component.onCompleted: {console.log("isCurrentPAge", a.SideMenu.isCurrenPage)} } } } }
the error message i get is: TypeError: Cannot read property 'isCurrenPage' of undefined
what am i missing? -
i was suggested in dicord by @GrecKo to change:
Component.onCompleted: {console.log("isCurrentPAge", a.SideMenu.isCurrenPage)}
to:
Component.onCompleted: {console.log("isCurrentPAge", a.T.SideMenu.isCurrenPage)}
apparently the alias is not just for object instantiating..