将QML信号连接到C ++ 11 lambda插槽(Qt 5) [英] Connect QML signal to C++11 lambda slot (Qt 5)

查看:140
本文介绍了将QML信号连接到C ++ 11 lambda插槽(Qt 5)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将QML信号连接到常规C ++插槽很容易:

Connecting a QML signal to a regular C++ slot is easy:

// QML
Rectangle { signal foo(); }

// C++ old-style
QObject::connect(some_qml_container, SIGNAL(foo()), some_qobject, SLOT(fooSlot()); // works!

但是,无论如何尝试,我似乎都无法连接到C ++ 11 lambda函数插槽

However, no matter what I try, I cannot seem to be able to connect to a C++11 lambda function slot.

// C++11
QObject::connect(some_qml_container, SIGNAL(foo()), [=]() { /* response */ }); // fails...
QObject::connect(some_qml_container, "foo()", [=]() { /* response */ }); // fails...

两次尝试均因函数签名错误而失败(没有QObject :: connect重载

Both attempts fail with a function signature error (no QObject::connect overload can accept these parameters). However, the Qt 5 documentation implies that this should be possible.

不幸的是,Qt 5示例始终将C ++信号连接到C ++ lambda插槽:

Unfortunately, Qt 5 examples always connect a C++ signal to a C++ lambda slot:

// C++11
QObject::connect(some_qml_container, &QMLContainer::foo, [=]() { /* response */ }); // works!

此语法不适用于问ML信号,如QMLContainer :: foo签名在编译时未知(并且手动声明QMLContainer :: foo不利于使用QML的目的。)

This syntax cannot work for a QML signal, as the QMLContainer::foo signature is not known at compile-time (and declaring QMLContainer::foo by hand defeats the purpose of using QML in the first place.)

我想做的是可能的吗?如果是这样,那么QObject :: connect调用的正确语法是什么?

Is what I'm trying to do possible? If so, what is the correct syntax for the QObject::connect call?

推荐答案

Lambdas等仅适用于新语法。如果您找不到将QML信号作为指针的方法,那么我认为这是不可能的。

Lambdas etc only work with new syntax. If you can't find a way to give QML signal as a pointer, then I think it is not directly possible.

如果这样,您有一个解决方法:创建一个虚拟信号路由QObject子类,仅包含信号,每个您要路由的QML信号一个。然后使用旧的connect语法将QML信号连接到该哑类实例的相应信号。

If so, you have a workaround: create a dummy signal-routing QObject subclass, which only has signals, one for every QML signal you need to route. Then connect QML signals to corresponding signals of an instance of this dummy class, using the old connect syntax.

现在,您有了可以使用新语法的C ++信号,并且

Now you have C++ signals you can use with the new syntax, and connect to lambdas.

该类还可以具有一个辅助方法,以自动实现从QML到该类信号的连接,该方法将利用QMetaObject反射机制和适当的信号命名使用与 QMetaObject :: connectSlotsByName 相同的原理。另外,您也可以对QML-router信号连接进行硬编码,但仍将其隐藏在路由器类的方法中。

The class could also have a helper method, to automate connections from QML to signals of the class, which would utilize QMetaObject reflection mechanisms and a suitable signal naming scheme, using same principle as QMetaObject::connectSlotsByName uses. Alternatively you can just hard-code the QML-router signal connections but still hide them inside a method of the router class.

未经测试...

这篇关于将QML信号连接到C ++ 11 lambda插槽(Qt 5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆