其他分享
首页 > 其他分享> > 是否可以在C QObject :: connect()中连接QML对象的现有信号?

是否可以在C QObject :: connect()中连接QML对象的现有信号?

作者:互联网

QML TreeView的信号名为:doubleClicked(QModelIndex)

参考:https://doc.qt.io/qt-5.10/qml-qtquick-controls-treeview.html#doubleClicked-signal

它可以将现有信号连接到C QObject :: connect()中.

我尝试了这个:

QQmlApplicationEngine engine;
QObject *myTreeMenu = engine.rootObjects().at(0)->findChild<QObject*>("myTreeMenu");
connect(myTreeMenu , SIGNAL(doubleClicked(QModelIndex)), this, SLOT(slotModelClicked(QModelIndex)));

但我收到此返回错误:

QObject::connect: No such signal TreeView_QMLTYPE_63_QML_68::doubleClicked(QModelIndex) in '...'
QObject::connect:  (sender name:   'myTreeMenu ')

解决方法:

documentation for Qt 5.11解释了为什么这不是使用C和QML的最佳方法.我建议您改为在C对象中公开一个插槽或Q_INVOKABLE,然后在onDoubleClicked处理程序中调用它:

Q_INVOKABLE void doStuff();

在QML中:

onDoubleClicked: cppObject.doStuff()

该文档有一个“之前和之后”的示例来证明这一点;这是大部分:

With this approach, references to objects are “pulled” from QML. The
problem with this is that the C++ logic layer depends on the QML
presentation layer. If we were to refactor the QML in such a way that
the objectName changes, or some other change breaks the ability for
the C++ to find the QML object, our workflow becomes much more
complicated and tedious.

Refactoring QML is a lot easier than refactoring C++, so in order to
make maintenance pain-free, we should strive to keep C++ types unaware
of QML as much as possible. This can be achieved by “pushing”
references to C++ types into QML:

06002

The QML then calls the C++ slot directly:

06003

With this approach, the C++ remains unchanged in the event that the
QML needs to be refactored in the future.

In the example above, we set a context property on the root context to
expose the C++ object to QML. This means that the property is
available to every component loaded by the engine. Context properties
are useful for objects that must be available as soon as the QML is
loaded and cannot be instantiated in QML.

07001 demonstrates an alternative approach where QML
is made aware of a C++ type so that it can instantiate it itself.

标签:c,qt,qml,signals-slots
来源: https://codeday.me/bug/20191012/1901282.html