QT 5.7 QML - Reference Error: Class is not defined

半城伤御伤魂 提交于 2019-12-25 08:13:39

问题


I get the "qrc:/main_left.qml:23: ReferenceError: CppClass is not defined" when I run the below code. This code tries to change the position of a rectangle in a window.

Main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

#include <QQmlContext>

#include "cppclass.h"
#include "bcontroller.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    //QGuiApplication app(argc, argv);

    BController c;

    CppClass cppClass;

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("CppClass", &cppClass);

    engine.load(QUrl(QStringLiteral("qrc:/main_left.qml")));


    return app.exec();
}

main_left.qml

import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 1.2

Rectangle {
    visible: true
    width: 640
    height: 480

    property int index: 0

    Text {
        text: controller.name
        anchors.centerIn: parent
    }
    Image{
        id:imageLeft
        anchors.fill: parent
        source:"imageLeft.jpg";
    }

    Connections {
        target: CppClass

        onPosUpdate: {
            rect.x = currentPos
        }
    }

    Button {
        id: button1
        x: 163
        y: 357
        text: qsTr("Change Position")
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 20
        anchors.horizontalCenter: parent.horizontalCenter
        onClicked: CppClass.getCurrentPos()
    }

    Rectangle {
        id: rect
        width: parent.width/2
        height: parent.height/2
        color: "transparent"
        border.color: "red"
        border.width: 5
        radius: 10
    }

    MouseArea {
        anchors.fill: parent
        onClicked: controller.setName(++index)
    }
}

cppclass.cpp

#include "cppclass.h"
#include <QtQuick>
#include <string>

CppClass::CppClass(QObject *parent) : QObject(parent)
{

}

CppClass::~CppClass()
{

}

void CppClass::getCurrentPos()
{
    int pos = rand() % 400;
    std::string s = std::to_string(pos);
    QString qstr = QString::fromStdString(s);
    emit posUpdate(qstr);
}

Please help!


回答1:


I think there is a problem with CppClass declaration in your main.cpp => CppClass cppClass; and your CppClass constructor is CppClass::CppClass(QObejct *parent); which means that you are missing the constructor parameter. Therefore,you have two possibilities

  • 1st : Try use your class without QObject *parent
  • 2nd: provide the QObject* parent for the contructor of CppClass when declaring it in main.cpp


来源:https://stackoverflow.com/questions/40543883/qt-5-7-qml-reference-error-class-is-not-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!