c++ - QML 与 C++ 通信

标签 c++ qt qml

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

相关文章:

Qt - 如何为菜单和小部件中的操作设置快捷上下文

c++ - 必须使用 '.*' 或 '->*' 来调用 'lessThan (...)' 中的指向成员函数的指针,例如 '(... ->* lessThan) (...)'

c++ - Qt:子对象可以在其父对象中组合吗?

c++ - 如何从 dll 中导出没有名称的函数

c++ - 可以比较两个指向成员函数的指针是否相等吗?

qt - 如何在不使用 id 的情况下从 ButtonStyle 获取父按钮?

javascript - 函数 toString() 不起作用

C++ 类型转换数组

c++ - 如何在不终止应用程序的情况下关闭 GLUT 窗口?

c++ - 将 qmlRegisterType 与 Q_ENUM 和 typedef 枚举一起使用