我该如何发消息?
我想要制作2个消息事件。首先,如果我的lineEdits中没有包含任何内容并按下按钮。必须出现错误消息“您还没有包含数据”。第二,如果我包括我的lineEdits并按下按钮。必须来的消息“你已经包含了数据。”但它对我不起作用。如果我按下按钮,程序保存空json。如果我在lineEdits中按下写入数据并按下按钮,则程序保存为普通的json。但无论我怎么写,程序总是会覆盖旧的json文件。我总是得到我存储数据的日志记录。
这是我的代码:
我的.Cpp文件:
#include "address_dialog.h"
#include "ui_address_dialog.h"
Address_Dialog::Address_Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Address_Dialog)
{
ui->setupUi(this);
connect(ui->pb_Cancel,SIGNAL(clicked(bool)),this,SLOT(close()));
//Save data in json on click
connect(ui->pb_save,SIGNAL(clicked(bool)),
this,SLOT(on_pb_save_clicked()));
}
Address_Dialog::~Address_Dialog()
{
delete ui;
}
void Address_Dialog::SaveDat()
{
m_address.mVorname= ui->le_Vorname->text();
m_address.mNachname= ui->le_Nachname->text();
m_address.mLand= ui->le_Land->text();
m_address.mName= ui->le_Name->text();
m_address.mPassword= ui->le_Password->text();
QJsonObject json_obj;
json_obj["FirstName"]= m_address.mVorname;
json_obj["MiddleName"]= m_address.mNachname;
json_obj["Country"]= m_address.mLand;
json_obj["NickName"]= m_address.mName;
json_obj["Password"]= m_address.mPassword;
//Open the file for Recording using the path specified
QString file_path = "C:/Users/frs/Documents/test_obj.json";
QFile save_file(file_path);
save_file.open(QIODevice::WriteOnly);
//if(!save_file.open(QIODevice::WriteOnly))
//QMessageBox::warning(0,"Error","Cannot open the file");
QJsonDocument json_doc(json_obj);
QString json_string = json_doc.toJson();
if(save_file.write(json_string.toLocal8Bit()))
QMessageBox::information(0,"Saving....",
"The item has been successfully added");
else
QMessageBox::critical(0,"Error","The item cannot be added");
save_file.close();
}
void Address_Dialog::on_pb_save_clicked()
{
SaveDat();
}
那是我的.H文件
#ifndef ADDRESS_DIALOG_H
#define ADDRESS_DIALOG_H
#include <QDialog>
#include <QMessageBox>
#include "address.h"
#include <QFile>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QString>
#include <QDir>
namespace Ui
{
class Address_Dialog;
}
class Address_Dialog : public QDialog
{
Q_OBJECT
public:
explicit Address_Dialog(QWidget *parent = 0);
~Address_Dialog();
Address m_address;//Creation of the Class object <=> /*QString mVorname,
// mNachname, mLand, mName, mPassword;*/
private slots:
void on_pb_save_clicked();
void SaveDat();
private:
Ui::Address_Dialog *ui;
};
#endif // ADDRESS_DIALOG_H
答案 0 :(得分:0)
我找到了解决方案。那很简单。我感谢大家的回应。
这是我的代码:
if(ui->le_Vorname->text().isEmpty() || ui->le_Nachname->text().isEmpty() ||
ui->le_Land->text().isEmpty() || ui->le_Name->text().isEmpty() ||
ui->le_Password->text().isEmpty())
{
ui->pb_save->setEnabled(false);
QMessageBox::critical(0,"Error","The item cannot be added");
}else
{
ui->pb_save->setEnabled(true);
save_file.write(json_string.toLocal8Bit());
QMessageBox::information(0,"Saving....", "The item has been successfully added");
}
save_file.close();