qml显示C++中的变量

#include <QObject>
#include <QTimer>
class TestObject : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int value READ getValue WRITE setValue NOTIFY valueChanged)
public:
    explicit TestObject(QObject *parent = nullptr);

    int getValue() const;
    void setValue(int value);
public slots:
    void slot_ReSet_Value();
signals:
    void valueChanged();
public:
    int value;
private:
    QTimer* timer;
};
TestObject::TestObject(QObject *parent) : QObject(parent)
{
    timer = new QTimer;timer->start(1000);
    connect(timer,SIGNAL(timeout()),this,SLOT(slot_ReSet_Value()));
}

int TestObject::getValue() const
{
    return value;
}

void TestObject::setValue(int values)
{
    value = values;
    emit valueChanged();
}

void TestObject::slot_ReSet_Value()
{
    static int n = 0;n++;
    setValue(n);
}
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTextCodec>
#include "TestObject.h"

int main(int argc, char *argv[]){
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    //加入个人内容
    TestObject *obj = new TestObject;
    engine.rootContext()->setContextProperty("obj",obj);

    return app.exec();
}
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    width: 640
    height: 320
    visible: true
    title: qsTr("Hello World")

    Text {
        id: name
        font.pointSize: 30
        text: obj.value
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值