QObject :: connect:在c ++ Qt 5.3中连接qml信号时没有这样的信号

时间:2014-11-17 12:57:31

标签: c++ qt qml signals-slots

我是使用Qt框架的新手。我不确定我哪里出错了。我试着查看许多相关材料,但仍然无法弄明白。

当我在qml文件中声明了一个信号时,我得到了“ QObject :: connect:没有这样的信号错误.. ”。

以下是代码:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    //QDeclarativeView view;
    QQmlApplicationEngine engine;

    testclass dsc;

    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:///test.qml")));
    while(component.isLoading());
    if (component.isError()) {
        qWarning() << component.errors();
    }

    QObject *object = component.create();
    QQuickItem *item = qobject_cast<QQuickItem*>(object);

    QObject::connect(item,SIGNAL(dsa(QVariant)),&dsc,SLOT(testslot(QVariant)));
    QObject::connect(&dsc,SIGNAL(dummysignal(QVariant)),&dsc,SLOT(testslot(QVariant)));
    dsc.dummysignal(&dsc);
    qDebug("Entered :");
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    return app.exec();
}

qml文件test.qml

Item {
    width: 800
    height: 500
    signal dsa(var obj)
    SystemPalette { id: palette }
}

测试类testclass.cpp

#include <QObject>

class testclass: public QObject
{
Q_OBJECT
public:
explicit testclass(QObject *parent = 0);

signals:
void dummysignal(QVariant);


public slots:


void testslot(QVariant);

};

我收到此错误:

QObject::connect: No such signal test_QMLTYPE_0::dsa(QVariant) in ..

3 个答案:

答案 0 :(得分:10)

问题在于您将dsa信号参数声明为&#39; var&#39; type,由qml引擎视为javascript值。因此,这会作为QJSValue传播到c ++中,而您尝试连接的信号的签名实际上是dsa(QJSValue)

如果您希望签名为dsa(QVariant),请在test.qml中更改您的信号声明,如下所示:

// test.qml

Item {
  signal dsa(variant obj)

  width: 800
  height: 500

  SystemPalette { id: palette }
}

这应该允许您在尝试使用语句

时进行连接
QObject::connect(item,SIGNAL(dsa(QVariant)),&dsc,SLOT(testslot(QVariant)));

(但首先你应该将你的广告位的签名更新为void testslot(QVariant); ...否则你只会在另一方面遇到同样的问题而没有这样的插槽&#39;误差)

FWIW,这是一个有用的调试技巧,没有这样的信号/插槽&#39;错误:

// Assuming you've instantiated QQuickItem* item
// This will print out the signature for every signal/slot on the object
// Make sure you include <QMetaObject>, <QMetaMethod>

const QMetaObject* metaObj = item->metaObject();
for (int i = 0; i < metaObj->methodCount(); ++i) {
    QMetaMethod method = metaObj->method(i);
    qDebug() << method.methodSignature();
}

答案 1 :(得分:1)

添加信号和插槽

#include <QObject>

class testclass: public QObject
{
    Q_OBJECT
public:
    explicit testclass(QObject *parent = 0);

signals:
    void dsa(QVariant parameter) {
        //some code
    }

public slots:
    void testslot(QVariant parameter) {
        //some code here
    }

    void testslot();
};

答案 2 :(得分:1)

QVariant是在Qt 5.2中用于映射var信号参数的正确类型,但它已在Qt 5.3中更改为映射到QJSValueChange C++ parameter type used for var parameters in QML declared signals

尽管如此,这已经在Qt 5.4中得到了回复,它将QVariant再次用于var信号参数: Revert mapping of var signal parameters to QJSValue