QML with C++

  • I am trying to make what is basically a gradient color picker, but the values are not being passed properly to the C++ part. The C++ is pretty much a copy of the documentation https://doc.qt.io/qt-5.14/qtqml-cppintegration-topic.html.

    #include "backend.h"
    Backend::Backend(QObject *parent) : QObject(parent)
        stop0Color = "#dfe9f3";
        stop1Color = "#ffffff";
    QString Backend::stop0()
        return stop0Color;
    QString Backend::stop1()
        return stop1Color;
    void Backend::setStop0(QString &stop0)
        if(stop0 == stop0Color)
        stop0Color = stop0;
        emit stop0Changed();
    void Backend::setStop1(QString &stop1)
        if(stop1 == stop1Color)
        stop1Color = stop1;
        emit stop1Changed();

    The button is simply a Rectangle with the gradient applied.

    import QtQuick 2.0
    import com.otwsoft.backend 1.0
    Item {
        property alias stop0Color: stop0.color
        property alias stop1Color: stop1.color
        implicitHeight: 200
        implicitWidth: 200
        Backend {
            id: backend
        Rectangle {
            id: button
            border.width: 5
            anchors.fill: parent
            gradient: Gradient {
                GradientStop {
                    id: stop0
                    position: 0
                    color: stop0Color
                GradientStop {
                    id: stop1
                    position: 1
                    color: stop1Color
        MouseArea {
            anchors.fill: parent
            onClicked: {
                console.log("initial stop0 = " + backend.stop0)
                console.log("initial stop1 = " + backend.stop1)
                backend.stop0 = stop0Color
                backend.stop1 = stop1Color
                console.log("stop0 = " + backend.stop0)
                console.log("stop1 = " + backend.stop1)

    and implemented like this

    GradientButton {
                    id: mountainRock
                    stop0Color: "#616161"
                    stop1Color: "#9bc5c3" 

    When the button is clicked, stop0 gets the stop1 color and stop1 is unchanged.

    qml: initial stop0 = #dfe9f3
    qml: initial stop1 = #ffffff
    qml: stop0 = #9bc5c3
    qml: stop1 = #ffffff

    I am probably missing something simple, but I have not been able to figure it out. Any help would be greatly appreciated.

  • @admkrk what I can see looks okay. Could you please also share the header in case there is an issue there.

  • Ahh, thank you. I thought I check the whole thing, but must have missed this line..

    Q_PROPERTY(QString stop1 READ stop1 WRITE setStop0 NOTIFY stop1Changed)

    A simple c&p error in the property that I failed to notice.

    Thanks again.

Log in to reply