Qt信号与自定义类型

时间:2017-09-01 22:47:31

标签: c++ qt qml

我想用带参数的Qt发送信号。此参数应该是自定义的结构。我已经用Q_DECLARE_METATYPE注册了它,但它不起作用,我得到一些奇怪的编译错误。

她是我的代码:

helper.h

#ifndef HELPER_H
#define HELPER_H

#include <QString>
#include <QMetaType>
struct result{
    QString info;
bool sugestion;
};
Q_DECLARE_METATYPE(result)

#endif // HELPER_H

analyser.h

#ifndef ANALYSER_H
#define ANALYSER_H
#include "helper.h"
#include <QObject>

class analyser: public QObject
{
    Q_OBJECT
public:
    void test()
    {
        result ret;
        ret.info="Hallo";
        emit show(ret);
    }
signals:
    void show(result r);
};

#endif // ANALYSER_H

qmlbackend.h

#ifndef QMLBACKEND_H
#define QMLBACKEND_H

#include <QObject>
#include "helper.h"
#include <QDebug>

class QmlBackend : public QObject
{
public slots:
    void hit(result res)
    {
        qDebug()<<"Working"<<res.info;
    }
 };

 #endif // QMLBACKEND_H

的main.cpp

#include <QDebug>
#include "qmlbackend.h"
#include "analyser.h"
#include <QGuiApplication>


int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QmlBackend b;
    analyser t;
    QObject::connect(&t,&analyser::show,&b,&QmlBackend::hit);
    t.test();

    return app.exec();
}

编译器输出:

moc_analyser.cpp: In static member function 'static void analyser::qt_static_metacall(QObject*, QMetaObject::Call, int, void**)':
moc_analyser.cpp:91:49: error: cannot declare pointer to 'void' member
         typedef void (analyser::*_t)(result );
                                             ^
moc_analyser.cpp:91:49: error: typedef '_t' is initialized (use decltype instead)
moc_analyser.cpp:92:35: error: '_t' does not name a type; did you mean '_o'?
         if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&analyser::show)) {
                               ^~
moc_analyser.cpp:92:38: error: expected '>' before '*' token
         if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&analyser::show)) {
                                  ^
moc_analyser.cpp:92:38: error: expected '(' before '*' token
moc_analyser.cpp:92:39: error: expected primary-expression before '>' token
         if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&analyser::show)) {
                                   ^
moc_analyser.cpp:92:62: error: '_t' does not name a type; did you mean '_o'?
         if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&analyser::show)) {
                                                          ^~
                                                          _o
moc_analyser.cpp:92:84: error: expected ')' before '{' token
         if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&analyser::show)) {
                                                                                ^
moc_analyser.cpp:96:9: error: expected primary-expression before '}' token
     }
     ^

有人可以告诉我为什么它不起作用或我必须改变什么?

1 个答案:

答案 0 :(得分:4)

这有点奇怪,证明你的代码生成了相同的错误但是如果我将result的结构名称更改为Result编译并正确执行(我建议你删除build文件夹然后编译)

我正在寻找Qt文档,它指出在使用Q_DECLARE_METATYPE时数据类型应该大写。