如何将QML中的ReferenceError解析为C ++对象

时间:2019-07-19 09:41:38

标签: c++ qt qml qt5

我在将c ++信号连接到QML窗口时遇到问题,所有事件按钮都可以正常工作,但是当我尝试附加信号时,我从输出控制台接收到“ ReferenceError”。

#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();
}

这个类,我也试图在我的两个信号上添加Q_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:{

            }
        }
    }
}

我希望c ++中发出的信号会修改QML窗口,但结果是:

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

2 个答案:

答案 0 :(得分:0)

您在类MainWindow中名称冲突:

    Q_INVOKABLE void onTimeChanged();

signals:
    void timeChanged(QString formatted_time);

因此,也许Qt无法理解您要使用的功能。尝试重命名其中之一

答案 1 :(得分:0)

我认为这是你的语法 你必须尝试:

    Connections{
        target: connection
        function onTimeChanged() {
        //doing stuff
      }
    }