Using a macro to create QObject derived classes

别等时光非礼了梦想. 提交于 2019-11-30 21:17:24

moc doesn't like macros very well. It expands them to some degree, but it fails when they get complicated¹.

You can try to replace signals: with public:² (i.e. manually expanding the signals macro), andtell moc that you want the function to be a signal by putting Q_SIGNAL in front of the function declaration.

Replace

signals:\
    void Notifier( Type value );\

with

public:\
    Q_SIGNAL void Notifier( Type value );\

¹: for some definition of complicated... I don't know when it fails, but I ran into some different problems in the past. From my experience my guess is that moc has problems when a macro body contains another macro, like signals in your example. But this is just a guess - maybe the kind of macros moc fails at is something else.

²: Before Qt 5, that used to be protected.

The vagaries of moc aside, your wrapper is not thread-safe. The property getter is not invoked from the correct thread. So I don't see any point of the wrapper. You might as well use the wrapped class directly from QML, not the wrapper.

To be thread-safe, your wrapper should be caching the wrapped property's value, so that the reads always happen from the local copy.

At that point you might as well write a fully dynamic wrapper that thread-safely forwards all properties from the wrapped object. Using the metaobject system you can generate everything on the fly - the copies of the property values, etc. As far as properties go, you can copy the entire binary descriptor as your wrapper pretends to have the same properties.

There is an excellent piece of code, you can google for qmltricks, it has everything you need as a good start.

You will need just one header. There is a room for extend to support read only properties or custom getters/setters.. but I would suggest to hae a look. I cant find an original.page now, saw a presentation on last Qt Summit, you probably can check qt site for hands-on materials.

Below a link on a github, there are several versions around available.

https://github.com/Cavewhere/lib-qt-qml-tricks/blob/master/include/QQmlHelpers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!