0
當我運行下面的代碼時,得到「qrc:/main_left.qml:23:ReferenceError:CppClass未定義」。此代碼嘗試更改窗口中矩形的位置。QT 5.7 QML - 參考錯誤:類未定義
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);
}
請幫幫忙!
宣佈它的時候,我注意到提供
QObject* parent
爲CppClass
的構造器我的錯誤。我忘了將'CppClass cppClass;'添加到我的main.cpp – mkocabas