我在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

./资源/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看到了另一个,因此完全无法连接它就不足为奇了。

如果您不熟悉C++的这一领域,请参见此tutorial,了解如何在头文件和源文件之间正确分割c++类的声明和定义。

关于c++ - QML与C++通信,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20831553/

10-09 06:23
查看更多