与C++代码中的 qml 对象交互
Interaction with qml objects from C++ code
我正在尝试使用QtQuick与文件中C++qml对象进行交互。但不幸的是,目前没有成功。知道我做错了什么吗?我尝试了 2 种方法,第一次的结果是 findChild() 返回 nullptr,在第二次尝试中我得到 Qml comnponent 未准备好错误。正确的方法是什么?
主要:
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
// 1-st attempt how to do it - Nothing Found
QObject *object = engine.rootObjects()[0];
QObject *mrect = object->findChild<QObject*>("mrect");
if (mrect)
qDebug("found");
else
qDebug("Nothing found");
//2-nd attempt - QQmlComponent: Component is not ready
QQmlComponent component(&engine, "Page1Form.ui.qml");
QObject *object2 = component.create();
qDebug() << "Property value:" << QQmlProperty::read(object, "mwidth").toInt();
return app.exec();
}
主.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
width: 640
height: 480
Page1 {
}
Page {
}
}
}
第 1 页:
import QtQuick 2.7
Page1Form {
...
}
第1页.表单.ui.qml
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
Item {
property alias mrect: mrect
property alias mwidth: mrect.width
Rectangle
{
id: mrect
x: 10
y: 20
height: 10
width: 10
}
}
findChild
将对象名称作为第一个参数。但不是身份证。
http://doc.qt.io/qt-5/qobject.html#findChild。
在您的代码中,您尝试使用 id mrect
进行查询。所以它可能不起作用。
在 QML 中添加objectName
,然后尝试使用对象名称进行findChild
访问。
如下所示(我没有尝试过。所以编译时出错的可能性):
在 QML 中添加对象名称
Rectangle
{
id: mrect
objectName: "mRectangle"
x: 10
y: 20
height: 10
width: 10
}
然后你的查找子,如下所示
QObject *mrect = object->findChild<QObject*>("mRectangle");
相关文章:
- QML 对象的销毁顺序
- 使用 createComponent 动态创建 QML 对象
- 可以在 QObject::connect() C++中连接 QML 对象现有信号?
- 如何删除 QML 对象
- 销毁 qml 对象后的信号槽连接
- 将 QObject 指针从 QML 对象传递到C++
- 使用C 访问QT / QML对象
- 如何使用 API 获取 QML 对象的 id 属性C++
- 如何在C++运行时更改QML对象的属性
- 与C++代码中的 qml 对象交互
- 如何从C++访问嵌套的 QML 对象
- 使用cpp代码从加载的qml访问qml对象
- 从C++访问 QML 对象
- 如何从C++调用 QML 对象的方法
- 从具有指定属性的C++创建 QML 对象
- 在现有 C++ QT 项目中实例化 QML 对象
- QML 对象属性的部分序列化
- 区分C++中QML对象的类类型
- 使用c++设置qml对象的属性
- 将qml对象添加到QGraphicsScene