gpt4 book ai didi

c++ - 从 QT 中的 C++ 代码访问 QML 元素

转载 作者:行者123 更新时间:2023-11-28 05:35:42 27 4
gpt4 key购买 nike

我正在尝试在 QT 中将 QML 与 C++ 结合使用,但目前还没有成功。我无法使用 rootObjects() 函数从 C++ 代码访问我的 QML 元素。我做错了什么?

qml部分:

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2

ApplicationWindow {
id: window
visible: true
width: 640
height: 520
title: qsTr("My app")

Item {
anchors.fill: parent
Rectangle {
id: rectangle1
x: 0
y: 0
width: 640
height: 370
color: "#ffffff"
}


Button {
id: startButton
x: 325
y: 425
text: qsTr("Start")
}
}
}

C++ 部分:

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

QObject *rootObject = engine.rootObjects().first();
qDebug() << rootObject->objectName();//prints ""


QObject *qmlObject = rootObject->findChild<QObject*>("window");// or "startButton"
//qDebug() << qmlObject->objectName(); //app fails, because window was not found


QList<QObject *> allQObjects = rootObject->findChildren<QObject *>();
for(int i=0;i< allQObjects.length();++i)
{
qDebug() << allQObjects[i]->objectName(); //prints everytime ""
}
qDebug() << "len: " << allPQObjects.length(); //prints 132


return app.exec();
}

最佳答案

一开始:如果不设置对象名就没有!

QML:

Rectangle { id : frame; objectName : "objFrame"  color : "blue" } 

Qt:

 QObject *pRootObject = m_pQmlView->rootObject();  
QObject *pobjFrame = m_pRootObject->findChild<QObject *>("objFrame");

反过来说:

问: m_pQmlView->rootContext()->setContextProperty( "_view", this );

QML:

 Component.onCompleted: {

/********************** Connections ***************************/

// connect signal MyView::retranslate() with slot retranslate
_view.retranslate.connect(retranslate)
}

关于c++ - 从 QT 中的 C++ 代码访问 QML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38345154/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com