A
A
Anthony2283572020-09-26 20:52:33
Qt
Anthony228357, 2020-09-26 20:52:33

How to change the properties of qml objects in qt qml in the created class?

there is a main.qml file

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Rectangle{
        x: 100
        y: 300
        width: 100;
        height: 100;
        MouseArea{
            anchors.fill: parent
        }
    }
}

main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("backend", &backend);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    return app.exec();
}

and let mainwindow.h
#include "QObject"
#include "QString"

class Backend: public QObject{
    Q_OBJECT
    Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
public:
    void change();
};

how to bind the change function in the mainwindow.cpp file to clicking on the rectangle and at the same time change its color?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jacob E, 2020-09-26
@Anthony228357

1. In real code, do not use absolute positioning, except in rare cases
2. You now have a MouseArea of ​​zero size, you need to use anchors.fill: parent
3. In the onClicked: backend.a handler, you did complete nonsense, firstly, the backend does not such a property, and secondly, you did not change it in any way, and did not even display it on the screen.
4. In order for the C++ class methods to become available in QML , they must be in the public slots
section . In this case, you could add a color property to the backend , and bind it to the Rectangle , like color: backend.color . Well and inonClicked will already call backend.change() , which will update the property.
In general, read articles , a book , other people's sources , and documentation so that such elementary questions do not arise.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question