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