我有一个小班无法正常工作,我不知道它有什么问题。编译器给出了消息:
main.cpp: error: undefined reference to 'CDetails::CDetails()'
这是代码中的快照:
//main.cpp
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QQmlContext>
#include <QDebug>
class CDetails : public QObject
{ Q_OBJECT
public:
CDetails() {}
~CDetails(void) {}
public slots:
void cppSlot(const QString &msg)
{ qDebug() << "Called the C++ slot with message:" << msg;
}
};
int main(int argc, char *argv[])
{ QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/testqml/main.qml"));
viewer.showExpanded();
CDetails *test = new CDetails();
QObject::connect((QObject*)viewer.rootObject(),
SIGNAL(qmlSignal(QString)),test,
SLOT(cppSlot(QString)));
return app.exec();
}
在main.qml中:
import QtQuick 2.0
Rectangle {
id: guide
width: 360
height: 360
signal qmlSignal(string msg)
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
property double scaleFactor: 1.0
property string iconUrl: "image.png"
MouseArea {
anchors.fill: parent
onClicked: {
guide.qmlSignal("Hello from QML")
}
}
}
更新:感谢关于构造函数的建议。现在错误是:
error: undefined reference to 'vtable for CDetails'
这里错过了什么?欢迎提出所有建议。
答案 0 :(得分:6)
错误:未定义引用'vtable for CDetails'
这里错过了什么?欢迎提出所有建议。
似乎你错过了主要功能之前的moc include。
#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QDebug>
class CDetails : public QObject
{ Q_OBJECT
public:
CDetails() {}
~CDetails(void) {}
public slots:
void cppSlot(const QString &msg)
{ qDebug() << "Called the C++ slot with message:" << msg;
}
};
#include "main.moc"
int main(int argc, char *argv[])
{ QGuiApplication app(argc, argv);
QQuickView view;
viewer.setMainQmlFile(QStringLiteral("qml/testqml/main.qml"));
viewer.showExpanded();
CDetails *test = new CDetails();
QObject::connect((QObject*)viewer.rootObject(),
SIGNAL(qmlSignal(QString)),test,
SLOT(cppSlot(QString)));
return app.exec();
}
...
TEMPLATE = app
TARGET = main
QT += quick
SOURCES += main.cpp
...
请注意,您还需要添加之前的自定义行,例如处理应用程序查看器等。
或者,您也可以将类和main.cpp分离,这意味着您可以将类的声明放入单独的标头中,然后将defintition放入单独的源文件中。
main.cpp将包含新建立的标头,您需要确保将新标头和源文件添加到qmake项目文件中的HEADERS
和SOURCES
变量中,分别通过moc处理。
答案 1 :(得分:4)
您缺少构造函数和析构函数的实现。快速修复:
class CDetails : public QObject
{ Q_OBJECT
public:
CDetails() {}
~CDetails(void) {}
...
};