如何从 C++ 修改 QML 文本 [英] How to modify a QML Text from C++

查看:21
本文介绍了如何从 C++ 修改 QML 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Qt 新手,我正在尝试从 C++ 代码修改 QML 文本(显示在屏幕中).我修改了文本,但它没有在屏幕上更新,所以我修改了文本变量但屏幕上的第一个文本.

I'm new to Qt and I'm trying to modify a QML Text (showed in the screen) from the C++ code. I get the text modified but it is not updated on the screen, so I have the text variable modified but the first text on the screen.

代码如下:

//main.cpp

#include <QApplication>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeItem>
#include <QDebug>
#include "qmlapplicationviewer.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));

    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/textModification/main.qml"));
    viewer.showExpanded();

    QDeclarativeEngine engine;
    QDeclarativeComponent component(&engine, QUrl::fromLocalFile("qml/textModification/main.qml"));
    QObject *object = component.create();

    QObject *item = qobject_cast<QDeclarativeItem*>(object);
    QObject *text = item->findChild<QObject*>("text1");
    qDebug() << "Text of 'text1' when it's created' -------->" << text->property("text");

    text->setProperty("text", "THIS WORKS!");

    qDebug() << "Text of 'text1' after modifying it -------->" << text->property("text");

    return app->exec();
}

//main.qml

import QtQuick 1.0

Item {
    id: item1
    objectName: "item1"
    width: 400
    height: 400

    Text {

        id: text1
        objectName: "text1"
        x: 0
        y: 0
        width: 400
        height: 29
        text: "This text should change..."
        font.pixelSize: 12
    }

}

有人可以帮我吗?

推荐答案

这可能不如使用 objectName 属性查找对象灵活,但这会很简单.

This may not be as flexible as finding the object using the objectName property, but this will be simple.

main.cpp

#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
#include <QGraphicsObject>


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

    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/TextTest/main.qml"));
    QObject *rootObject = viewer.rootObject();
    rootObject->setProperty("text1Text",QVariant("Change you text here..."));

    viewer.showExpanded();
    int returnVal = app.exec();
    delete rootObject;
    return returnVal;
}

main.qml

import QtQuick 1.0

Item {
    id: item1
    width: 400
    height: 400
    property alias text1Text: text1.text

    Text {
        id: text1
        width: 400
        height: 29
        color: "red"
        text: "This text should change..."
        font.pixelSize: 12
    }

}

这篇关于如何从 C++ 修改 QML 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆