我正在尝试将QML信号连接到C ++插槽,但是由于某种原因(可能是我很笨)QObject::connect
无法找到该插槽。
我尝试将来自qml的简单void
信号连接到没有参数的void
插槽。我已经对方法签名和名称进行了三重检查(我本来是传递字符串,但是为了修复错误,简化了方法签名)。
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();
}
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”