====== Accedere agli oggetti Qml dal C++ (Qt) ======
Autore: **//Fabio Di Matteo//** \\ Ultima revisione: **//30/11/2017 - 15:33//** \\ \\
In questo primo esempio cambieremo la proprieta' "text" di due oggetti qml.
//Ottengo il riferimento al mio oggetto qml
QObject *rootObject = engine.rootObjects().first(); //nodo root
QObject *qmlButton = rootObject->findChild("button0");
QObject *qmlTextEdit = rootObject->findChild("rect");
//Setto una proprieta'
qmlButton->setProperty("text", "Sono un Button");
qmlTextEdit->setProperty("text","Sono Un text Edit");
I vari widget qml vengono esposti al C++ tramite la property **objectName** Ecco il codice :
**main.cpp**
#include
#include
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
//Ottengo il riferimento al mio oggetto qml
QObject *rootObject = engine.rootObjects().first(); //nodo root
QObject *qmlButton = rootObject->findChild("button0");
QObject *qmlTextEdit = rootObject->findChild("rect");
//Setto una proprieta'
qmlButton->setProperty("text", "Sono un Button");
qmlTextEdit->setProperty("text","Sono Un text Edit");
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
**main.qml**
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MouseArea {
anchors.fill: parent
onClicked: {
console.log(qsTr('Clicked on background. Text: "' + textEdit.text + '"'))
}
Button {
id: button0
objectName: "button0"
x: 353
y: 94
text: qsTr("Button")
}
}
TextEdit {
id: textEdit
objectName: "rect"
text: qsTr("Enter some text...")
anchors.horizontalCenterOffset: -43
verticalAlignment: Text.AlignVCenter
anchors.top: parent.top
anchors.horizontalCenter: parent.horizontalCenter
anchors.topMargin: 101
Rectangle {
anchors.fill: parent
anchors.margins: -10
color: "transparent"
anchors.rightMargin: -10
anchors.bottomMargin: -14
anchors.leftMargin: -10
anchors.topMargin: -6
border.width: 1
}
}
}