I'm trying to learn more about QtQuick and QML. My current goal is to understand how to bind data from a C++ model to my view. So far I've been able to setup the model in my QML and get data from the model but I can't figure out how to update my data.
How do I setup two way binding for my C++ model? Below is the code I've written so far.
message.h
class Message : public QObject
{
Q_OBJECT
Q_PROPERTY(QString author READ getAuthor WRITE setAuthor NOTIFY authorChanged)
Q_PROPERTY(QString message READ getMessage WRITE setMessage NOTIFY messageChanged)
Q_SIGNALS:
void authorChanged(QString author);
void messageChanged(QString message);
public:
Message(QObject *parent = 0);
QString getAuthor();
void setAuthor(QString author);
QString getMessage();
void setMessage(QString message);
private:
QString _author;
QString _message;
};
message.cpp
#include "message.h"
Message::Message(QObject *parent) : QObject(parent)
{
}
QString Message::getAuthor()
{
return _author;
}
void Message::setAuthor(QString author)
{
if(author != _author)
{
_author = author;
emit authorChanged(author);
}
}
QString Message::getMessage()
{
return _message;
}
void Message::setMessage(QString message)
{
if(message != _message)
{
_message = message;
emit messageChanged(message);
}
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import com.butts.messaging 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Test"
Message {
id: testMessage
author: "Batman"
message: "Hello World!"
}
Flow {
TextField {
text: testMessage.message
}
Label {
text: testMessage.message
}
}
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "message.h"
int main(int argc, char *argv[])
{
qmlRegisterType<Message>("com.butts.messaging", 1, 0, "Message");
//Message msg = Message();
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
return app.exec();
}
P.S. I'm a giant noob at this so feel free to point out any other issues (formatting, standards, etc.) I have in my code, I need to learn somehow lol
Edit 1
After reading @derM's answer I changed my code to achieve what I wanted
TextField {
id: editor
//Binding model -> view
text: testMessage.message
//Binding model <- view
Binding {
target: testMessage
property: "message"
value: editor.text
}
}
Label {
id: display
//Binding model -> view
text: testMessage.message
}