我在 QML 与 C++ 通信时遇到问题。我已经按照预期使示例代码正常运行的所有步骤进行了操作。在处理这个小示例几个小时后,它归结为一条错误消息,我根本无法摆脱它:
./input/main.cpp:18: error:
no matching function for call to
'QObject::connect(QObject*&, const char*, Input*, const char*)'
&input, SLOT(cppSlot(QString)));
^
我在 related problem 上阅读了一些以前的帖子,仔细检查所有内容,显然一切看起来都是正确的。以下是详细信息:
./Sources/main.cpp
#include <QtGui/QGuiApplication>
#include <QtQml/QQmlApplicationEngine>
#include <QtQml/QQmlEngine>
#include <QQuickWindow>
#include <QtDeclarative>
#include <QObject>
#include <QDebug>
#include "Input.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDeclarativeView view(QUrl::fromLocalFile("input.qml"));
QObject *item = view.rootObject();
Input input;
QObject::connect(item, SIGNAL(qmlSignal(QString)),
&input, SLOT(cppSlot(QString)));
view.show();
return app.exec();
}
./Headers/Input.h
#ifndef INPUT_H
#define INPUT_H
#include <QObject>
#include <QDebug>
class Input : public QObject
{ public:
Input(){} // default constructor
Q_OBJECT
public slots:
void cppSlot(const QString &msg) {
qDebug() << "Called the C++ slot with message:" << msg;
}
};
#endif // INPUT_H
./Input.pro
QT += qml quick sensors xml
QT += declarative
SOURCES += \
main.cpp \
Input.cpp
RESOURCES += \
Input.qrc
OTHER_FILES += \
Input.qml
HEADERS += \
Input.h
./Resources/Input.qrc
/
Input.qml
我正在使用的连接来自 qtproject示例:
QObject::connect(item, SIGNAL(qmlSignal(QString)),&myClass, SLOT(cppSlot(QString)));
也许有人知道这里缺少什么?谢谢!
最佳答案
请真正的class Input
站起来好吗?
您似乎在 Input.h 中定义了一个,在 Input.cpp 中定义了另一个。其中只有一个是 Q_OBJECT 和 QObject 子类。 main.cpp 正在从 Input.h 中看到另一个,因此无法连接它也就不足为奇了。
参见例如 tutorial了解如何在头文件和源文件之间正确拆分 C++ 类声明和定义(如果您不熟悉 C++ 的这一领域)。
关于c++ - QML 与 C++ 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20831553/