WUT_Computer_Science/EGUI/lab1/blogentry.cpp

90 lines
2.2 KiB
C++
Raw Normal View History

2022-04-04 21:22:50 +02:00
#include "blogentry.h"
#include "ui_blogentry.h"
2022-04-04 21:56:57 +02:00
#include <QDateTime>
2022-04-05 00:26:36 +02:00
#include <QJsonObject>
#include <QFile>
#include <QJsonDocument>
2022-04-06 01:06:01 +02:00
#include <QJsonArray>
2022-04-04 21:22:50 +02:00
blogEntry::blogEntry(QWidget *parent) :
QWidget(parent),
ui(new Ui::blogEntry)
{
ui->setupUi(this);
2022-04-04 21:56:57 +02:00
QString Time = QTime::currentTime().toString();
QString Date = QDate::currentDate().toString();
ui -> dateTime -> setText(Date + " " + Time);
2022-04-05 00:26:36 +02:00
qDebug() << "blogEntry id: " << userId;
2022-04-04 21:56:57 +02:00
qDebug() << Time;
2022-04-04 21:22:50 +02:00
}
blogEntry::~blogEntry()
{
delete ui;
}
2022-04-05 00:26:36 +02:00
void blogEntry::setUserId(const QString &userId)
{
qDebug() << "blogEntry id: " << userId;
this->userId = userId;
ui -> ownerID -> setText("Owner ID: " + userId);
}
2022-04-06 01:06:01 +02:00
void blogEntry::setBlogId(const QString &blogId)
{
this->blogId = blogId;
}
2022-04-05 00:26:36 +02:00
QJsonObject blogEntry::readJsonFile(const QString title)
{
QFile file(title);
2022-04-06 01:06:01 +02:00
file.open( QIODevice::ReadWrite);
2022-04-05 00:26:36 +02:00
QByteArray bytes = file.readAll();
file.close();
QJsonDocument document = QJsonDocument::fromJson( bytes );
return document.object();
}
void blogEntry::saveJsonFile(QJsonObject &users, const QString name) const
{
QFile jsonFile(name);
QJsonDocument document;
document.setObject( users );
QByteArray bytes = document.toJson( QJsonDocument::Indented );
jsonFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate );
QTextStream iStream( &jsonFile );
// iStream.setCodec( "utf-8" );
iStream << bytes;
jsonFile.close();
}
void blogEntry::saveEntry()
{
ui -> textEdit -> setReadOnly(true);
ui -> lineEdit -> setReadOnly(true);
2022-04-06 01:06:01 +02:00
QJsonObject blogsFile = readJsonFile("blogs.json");
QJsonObject blogEntryJson = blogsFile[blogId].toObject();
QJsonObject entry;
entry["title"] = ui -> lineEdit -> text();
2022-04-05 00:26:36 +02:00
QString Time = QTime::currentTime().toString();
QString Date = QDate::currentDate().toString();
2022-04-06 01:06:01 +02:00
entry["datetime"] = Time + " " + Date;
entry["content"] = ui -> textEdit -> toPlainText();
QJsonArray items = blogEntryJson["items"].toArray();
items.append(entry);
blogEntryJson.insert("items", items);
blogsFile.insert(blogId, blogEntryJson);
2022-04-05 00:26:36 +02:00
saveJsonFile(blogsFile, "blogs.json");
}
void blogEntry::on_saveEntry_clicked()
{
saveEntry();
}