簡體   English   中英

如何從 C++ 設置 QML 屬性

[英]How to set QML properties from C++

我正在嘗試做一個簡單的任務,比如從 C++ 更改某些 QML 對象的屬性(文本:),但我失敗了。 任何幫助表示贊賞。

我沒有收到任何錯誤,窗口顯示出來,只是 text 屬性沒有像(至少我認為)應該的那樣改變。 有什么我沒有做錯的嗎?!

我正在嘗試的是這樣的:

主程序

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQuickItem>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QString>

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

    QQmlApplicationEngine engine;


    QQmlComponent component(&engine, QUrl::fromLocalFile("main.qml"));
    QObject *object = component.create();

     engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    QString thisString = "Dr. Perry Cox";

    object->setProperty("text", thisString);  //<--- tried  instead of thisString putting "Dr. ..." but nope.
    delete object;



    return app.exec();
}

主文件

import QtQuick 2.2
import QtQuick.Window 2.1

Window {
    visible: true
    width: 360
    height: 360

    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }

    Text {
        id: whot
        text: ""
        anchors.centerIn: parent
        font.pixelSize: 20
        color: "green"
    }
}

當你調用QObject *object = component.create(); 您可以訪問根上下文,即Window組件及其屬性。

要訪問Text屬性,您可以像這樣創建屬性別名:

Window {
    property alias text: whot.text
    ...
    Text {
        id: whot
        text: ""
        ...
    }
}

這將使您能夠從Window的上下文中訪問whottext屬性。

還有另一種稍微迂回的方式。 objectName屬性而不是id (或者如果您仍然需要id )分配給whot

Text {
    id: whot // <--- optional
    objectName: "whot" // <--- required
    text: ""
    ...
 }

現在您可以在代碼中執行此操作:

QObject *whot = object->findChild<QObject*>("whot");
if (whot)
    whot->setProperty("text", thisString);

附帶說明:我認為您不應該在調用app.exec()之前刪除該object 否則,它將......好吧,被刪除。 :)

#include <QQmlContext>
#include <qquickview.h>
#include <qdir.h>

QQmlApplicationEngine engine;
QString root = QCoreApplication::applicationDirPath();
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
        return -1;
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow*>(topLevel);
window->setProperty("root", root);

對於 qml

ApplicationWindow  {
    property string root
    onRootChanged: {
        console.log("root : "+ root);
    }
}

對於 QML 屬性,您應該改用QQmlProperty

QQmlProperty::write(whot, "text", thisString);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM