QObject :: connect没有这样的插槽(QML,C ++)

时间:2019-05-17 06:21:58

标签: c++ qt slots

我正在尝试将QML信号连接到C ++插槽,但是由于某种原因(可能是我很笨)QObject::connect无法找到该插槽。

我尝试将来自qml的简单void信号连接到没有参数的void插槽。我已经对方法签名和名称进行了三重检查(我本来是传递字符串,但是为了修复错误,简化了方法签名)。

main.cpp

class QMLSignalHandler : public QObject{
public:
    explicit QMLSignalHandler(QObject* parent=nullptr) : QObject (parent){}
public slots:
    void handleNewTask(){
        qDebug() << "Hello";
    }
};

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

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);
    auto *ctxt = engine.rootContext();

    QQuickWindow * window = qobject_cast<QQuickWindow *>(engine.rootObjects().value(0));
    QMLSignalHandler handler;

    //No compile-time error, but as soon as I run, it gives No such slot QObject::handleNewTask()
    QObject::connect(window, SIGNAL(addTask()), &handler, SLOT(handleNewTask()));

    return app.exec();
}

main.qml

Window {
    id: rootWindow
    width: 300
    height: 400
    title: qsTr("Hello World")
    visible: true
    signal addTask
    Button{ 
        text: "test"
        onClicked: addTask()
        anchors.bottom: taskList.bottom
    }
}

正如我所说,信号和插槽在应该连接的时候没有连接。该程序在运行时应输出“ Hello”

0 个答案:

没有答案