c++qtqmlqtquick2qquickitem

How to create custom Quick QML Item with predefided states


I am quite new to Qt, so I am probably asking a pretty obvious question.

I would like to create a super type for all of my custom QML GUI elements that I want to create in C++. This super type is supposed to add predefined states to a QML Item. Something alike to this:

    import StatedGuiElement 1.0
    import QtQuick 2.0

    Item {
        width: 300; height: 200

        StatedGuiElement {
            id: aStatedGuiElement
            anchors.centerIn: parent
            width: 100; height: 100
            //some visible Custom Gui Elements
    states:[
        State {
            name: "A_STATE"

        },
        State {
            name: "ANOTHER_STATE"
        }]
}

I know how to create a simple custom Item from this tutorial (http://doc.qt.io/qt-5/qtqml-tutorials-extending-qml-example.html). I guess the states could be defined by using an enum in the C++ class which inherits from QQuickItem. However, this tutorial does not show how to create more complex Qt Quick elements like the state list.

class StatedGuiElement : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QString name READ name WRITE setName)
    //pass States via Q_PROPERTY?
public:
    //define Enum for fixed States here?
    //ENUM STATES {A_STATE, ANOTHER_STATE}
    StatedGuiElement( QQuickItem *parent = 0);

    QString name() const;
    void setName(const QString &name);


private:
    QString m_name;
    //Some List of States?


signals:

public slots:
};

So the questions I am wondering about are as follows:


Solution

  • First you create your StatedGuiElement as a QQuickItem subclass.

    Then you crate a StatedGuiElement.qml, import the package that contains the C++ element, make a StatedGuiElement {} inside, add your states in QML to it, then you can use StatedGuiElement in your project. It will be the one with the QML extra stuff predefined in it.

    This assumes the element actually has things you need to implement in C++. If not then it would not make sense to have a C++ element at all. I am not sure whether old C++ state classes will work with QML, probably not, and using the QML states from C++ will be anything but convenient, so you really should do the states in QML, on top of whatever C++ stuff you may have.