我得到" qrc:/main_left.qml:23:ReferenceError:未定义CppClass"当我运行以下代码时。此代码尝试更改窗口中矩形的位置。
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();
}
&#13;
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)
}
}
&#13;
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);
}
&#13;
请帮忙!
答案 0 :(得分:1)
我认为CppClass
=&gt;中的main.cpp
声明存在问题。 CppClass cppClass;
和CppClass
构造函数为CppClass::CppClass(QObejct *parent);
,这意味着您缺少构造函数参数。
因此,您有两种可能性
QObject *parent
QObject* parent
CppClass
的构造函数提供main.cpp