使用c++设置qml对象的属性

Set property of qml object using c++

本文关键字:属性 对象 qml c++ 设置 使用      更新时间:2023-10-16

我试过

 widget->setProperty("text1Text", QVariant("After..."));

在我的C++中,和

 Button
 {
    property alias text1Text: text1.text
    Text
    {
        id: text1
        text: "Initial"
    }   
 }

以qml表示。小部件是一个QQuickWidget对象。我做错了什么?

请参阅从C++与QML对象交互。

如果使用QQmlEngine:

// Using QQmlComponent
QQmlApplicationEngine engine;
...
QObject * root = engine.rootObjects().first();

如果您正在使用QQuickView:

QQuickView view;
...
QObject * root = view.rootObject();

获取text1:

// Update Qml file
Text
{
    id: text1
    text: "Initial"
    objectName: id
} 
// Find text1 in c++
QObject * o1 = root->findChild<QObject *>(QStringLiteral("text1"));
QQuickItem *text1 = qobject_cast<QQuickItem*>(o1);
// Set property
text1->setProperty("text", QVariant());