gpt4 book ai didi

c++ - QT 5.7 QML - 引用错误 : Class is not defined

转载 作者:行者123 更新时间:2023-11-28 05:26:00 26 4
gpt4 key购买 nike

当我运行下面的代码时,我得到了“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; 中的 CppClass declaration 有问题并且您的 CppClass 构造函数是 CppClass::CppClass(QObejct *parent); 这意味着您缺少构造函数参数。因此,你有两种可能

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

关于c++ - QT 5.7 QML - 引用错误 : Class is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40543883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com