2017-10-06 7 views
0

Je suis en train d'interagir avec un objet qml de fichier C++ en utilisant QtQuick. Mais malheureusement, sans succès pour le moment. Une idée de ce que je fais mal? J'ai essayé 2 façons de le faire, résultat de la première était que findChild() a retourné nullptr, et dans la deuxième tentative, je reçois Qml comnponent n'est pas prêt erreur. Quelle est la bonne façon de le faire?Interaction avec des objets QML de code C++

principal:

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 
    } 
} 

Répondre

2

findChild prend le nom de l'objet en tant que premier paramètre. Mais pas ID.

http://doc.qt.io/qt-5/qobject.html#findChild.

Ici, dans votre code, vous essayez d'interroger avec l'ID mrect. Donc ça peut ne pas fonctionner.

Ajoutez objectName dans votre QML, puis essayez d'accéder à findChild en utilisant le nom d'objet.

Quelque chose comme ci-dessous (je n'y suis pas allé si les chances d'erreurs de compilation.):

Ajouter objectName dans QML

Rectangle 
{ 
    id: mrect 
    objectName: "mRectangle" 
    x: 10 
    y: 20 
    height: 10 
    width: 10 
} 

Et puis votre findChild comme indiqué ci-dessous

QObject *mrect = object->findChild<QObject*>("mRectangle");