.message.h
#ifndef MESSAGE_H
#define MESSAGE_H
#include <QObject>
#include <QQuickItem>
class Message : public QObject
{
Q_OBJECT
public:
explicit Message(QObject *parent = 0);
public slots:
void doMessageChange();
signals:
void messageChanged(QString value);
private:
int m_counter;
QString m_message;
explicit Message(const Message & rhs) = delete;
Message& operator = (const Message& rhs) = delete;
};
#endif // MESSAGE_H
message.cpp
#include "message.h"
#include <iostream>
Message::Message(QObject *parent):
QObject (parent),
m_counter(0),
m_message("Hello New World! %1")
{
}
void Message::doMessageChange()
{
++m_counter;
emit messageChanged(m_message.arg(m_counter));
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "message.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Message my_msg;
auto root_context = engine.rootContext();
root_context->setContextProperty("messageClasee",&my_msg);
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);
return app.exec();
}
main.qml
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Connections{
target:messageClasee
onMessageChanged: textId.text = value;
}
Column{
Text {
id :textId
text: qsTr("Hellow New World")
font.pointSize: 20
}
Button{
text:"Change Text"
onClicked: messageClasee.doMessageChange()
}
}
}