我正在尝试使用 QtQuick 与来自 C++ 文件的 qml 对象进行交互。但遗憾的是暂时没有成功。知道我做错了什么吗?我尝试了两种方法,第一种方法的结果是 findChild() 返回了 nullptr,第二次尝试时我得到了 Qml 组件未准备好 错误。正确的做法是什么?
主要内容:
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 {
}
}
}
Page1.qml:
import QtQuick 2.7
Page1Form {
...
}
Page1.Form.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中添加objectName
Rectangle
{
id: mrect
objectName: "mRectangle"
x: 10
y: 20
height: 10
width: 10
}
然后你的 findChild 如下图所示
QObject *mrect = object->findChild<QObject*>("mRectangle");
关于c++ - 与 C++ 代码中的 qml 对象交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46611399/