[英]Interaction with qml objects from C++ code
我正在嘗試使用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();
}
main.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
將對象名稱作為第一個參數。 但不是ID。
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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.