【问题标题】:QT 5.7 QML - Reference Error: Class is not definedQT 5.7 QML - 参考错误:未定义类
【发布时间】:2017-03-25 10:36:51
【问题描述】:

当我运行以下代码时,我得到“qrc:/main_left.qml:23: ReferenceError: CppClass is not defined”。这段代码试图改变一个矩形在窗口中的位置。

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

ma​​in_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);
}

请帮忙!

【问题讨论】:

  • 我注意到了我的错误。我忘了在我的 main.cpp 中添加 CppClass cppClass;

标签: c++ qml qt5


【解决方案1】:

我认为您的main.cpp => CppClass cppClass; 中的CppClass 声明 有问题,而您的CppClass 构造函数是CppClass::CppClass(QObejct *parent);,这意味着您缺少构造函数参数. 所以,你有两种可能

  • 1st :尝试在没有QObject *parent 的情况下使用您的课程
  • 2nd:在main.cpp中声明时,为CppClass的构造器提供QObject* parent

【讨论】:

    猜你喜欢
    • 2012-11-04
    • 2019-08-17
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2023-03-14
    相关资源
    最近更新 更多