简体   繁体   中英

How to resolve ReferenceError in QML to c++ object

I have a problem to connect c++ signal into QML window, all events button work correctly but when i try to attach the signal i recive "ReferenceError" from output console.

#include <QApplication>

#include <QQuickWidget>
#include <QQmlContext>
#include <QQuickView>

#include "settings.h"
#include "settingswindow.h"
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);



    QQuickView wdg;

    MainWindow mywnd;
    wdg.engine()->rootContext()->setContextProperty("connection", &mywnd);
    wdg.setSource(QUrl("qrc:/qml_vertical_7p/MainWindow.qml"));
    wdg.show();

    return  app.exec();
}

This the class, i have also tried to add Q_SIGNAL on my two signal

#include <QObject>
#include <QQuickWidget>
#include <QQmlContext>
#include <QQmlEngine>

#include <QTimer>
#include <QTime>
#include <QDate>


#include <QDebug>

class MainWindow : public QObject
{
    Q_OBJECT

private:
    QString _windowPrefix;
    const QString _mainWindowName = "MainWindow.qml";

    QQuickWidget *_window;

    QTimer _timer;


public:
    explicit MainWindow(QObject *parent = nullptr);
    void Show();

    Q_INVOKABLE void secreetButtonPressed();
    Q_INVOKABLE void secreetButtonReleased();
    Q_INVOKABLE void onTimeChanged();

signals:
    void timeChanged(QString formatted_time);
    void dataChanged(QString formatted_data);
}
import QtQuick 2.4
import QtQuick.Controls 2.0

Item
{
    id:wnd
    visible: true
    width: form.height
    height: form.width

    Page
    {
        rotation: 90

        MainWindowForm
        {
            id: form
            x: 0
            y: -800

            mouseArea.onPressed: {
                connection.secreetButtonPressed()
            }
            mouseArea.onReleased: {
                connection.secreetButtonReleased()
            }
        }

        Connections
        {
            target: connection
            onTimeChanged:{

            }
        }
    }
}

I expect that the emitted signal in c++ modifies the QML window but the result is:

QML Connections: Cannot assign to non-existent property "onTimeChanged"
ReferenceError: connection is not defined

You have names conflict in your class MainWindow:

    Q_INVOKABLE void onTimeChanged();

signals:
    void timeChanged(QString formatted_time);

So, maybe Qt can't understand what function you want to use. Try to rename one of it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM