how to save QJsonDocument to file - c++

I started learning Qt and i have a problem, basically i'm trying to make this simple app -3 line edits and one button that will get your name etc from line edits and put it into JSON file. Right now i'm able to get the data and put it into Qjson object and then put the object into Qjson document but i can't save the json document with a QFile.
I've tried to look it up but haven't found anything that works
void MainWindow::on_pushButton_clicked()
{
qDebug()<<"ok button clicked";
QString firstName=ui->NameEdit->text();
QString lastName=ui->LnameEdit->text();
QString age=ui->ageEdit->text();
QJsonObject user;
user["firstname"]=firstName;
user["lastname"]=lastName;
user["age"]=age;
qDebug()<<user;
QJsonDocument userDoc(user);
qDebug()<<userDoc;
QFile users("users.json");
users.open(QIODevice::WriteOnly);
//it is working to this point
users.write(userDoc.toJson());
users.close();
//when i open "users.json" file it's always empty
}

Related

How to run Python script from QT creator and print output to GUI

void MainWindow::on_pushButton_clicked()
{
QProcess p;
// get values from ini file
settings->setValue("EMail", ui->lineEditEMail->text());
settings->setValue("Password", ui->lineEditPassword->text());
settings->setValue("Chronological", ui->checkBox->isChecked());
settings->setValue("Current_info", ui->checkBox_2->isChecked());
settings->endGroup();
settings->sync();
// launch python code for login
QString program( "C:/projects/build-test3-Desktop_Qt_6_4_0_MinGW_64_bit-Debug/venv/Scripts/python.exe");
QStringList args = QStringList() << "index.py";
QProcess::execute( program, args );
}
I have this function that is executed after a button is clicked and I need to print the output of "index.py" in to my app. What widget should I use and how? From what I read QTextBrowser should do the trick but I'm not sure how to use it.
This is how my GUI looks like. I'd like to use to output my results somewhere in button right. I didn't add the widget yet, because I'm not sure QTextBrowser is the one I need
The widget you could use for this purpose is QTextEdit (you can set it to be read-only from the graphical user interface).
But if you want to get the output of the execution, you will need a proper instance of QProcess and call the QProcess::readAllStandardOutput() member function to get the standard output.
You may also be interested by QProcess::readAllStandardError() to get the errors in case of failure.
Edit (simple/basic example):
QProcess p;
p.start("path/to/python.exe", QStringList("script.py"));
p.waitForFinished();
QByteArray p_stdout = p.readAllStandardOutput();
QByteArray p_stderr = p.readAllStandardError();
// Do whatever you want with the results (check if they are not empty, print them, fill your QTextEdit contents, etc...)
Note: If you don't want to be blocking with QProcess::waitForFinished(), you can use a signal/slots connection on QProcess::finished() signal.

Data does not get reflected in real time in Qt TexttEdit widget

I am trying to scan files and its sub directory , the code from Qt Examples works absolutely fine and displays data with QDebug() .
However when i try to it.next() data to a Qlable or textEdit widget , it doesn't show the data in realtime. The data is reflected after the it.hasNext() gets completed. I want to show real time scanning status in the textedit box - Self is new to Qt.
How to show the status for the file being scanned in real time, in the Qt textEdit widget ?
Code is given below .
void MainWindow::findFilesRecursively(QDir rootDir) {
QDirIterator it(rootDir, QDirIterator::Subdirectories);
while(it.hasNext()) {
qDebug() << it.next();
// ui->textEdit->append(it.next()); <<<<<<---- This is note getting updated realtime,
Data get populated after the scan in complted.
}
}
Error
enter image description here
This may or may not be your problem, but do you understand what your code is trying to do?
Your debug statement calls it->next(). You then in your commented-out code call it->next() a second time. If your directory only contains a single file, you've already dumped it. The debug statement eats it.
What you need instead:
QString fName = it->next();
qDebug() << fName;
ui->textEdit->append(fName);
I'm not absolutely positive this is your problem, because I don't know if you commented out your qDebug when you ran it or how big your directory is. There might be something else going on.

How to save a text file directly without using QfileDialog box?

This is my sample UI, the white box is a textbox which will have some items, my main question is that when i click "Save/Refresh" qpushbutton, i want to save all of the qtextbox text into a textfile/sample_name.xml into a designated folder, but i dont wanna go through Qfiledialog box and having to decide/browse a location in which the file needs to be saved, i just want it to be saved at a fixed place in C-drive ,
and also the text in the qtextbox should again be loaded with that sample_name.xml file, i know the content is gonna be the same as i just saved it , but still i need it for some other functionality.
How can i acheive this without the involvement of qfiledialog ?
Using Qt classes, the required code could look like that:
The following code should be in a "slot" function that is connected to the clicked() signal of your button.
QString text = ui->textField->text(); // get the text from your UI component
QFile file(QStringLiteral("C:/fixed_path.txt")); // define the file to write
if (file.open(QIODevice::WriteOnly)) // open the file and check that everything is ok
{
file.write(text.toUtf8()); // write your data in the file
file.close(); // close the file
}
You will have to provide a static path within the function that listens at your Save button. Your listener function would be of a similar format:
void save(){
//assuming content of textbox has been stored in variable 'content'
ofstream myfile;
myfile.open ("path_to_file", ios::trunc);
myfile << content;
myfile.close();
}
Similarly on reopening this view, you'll run a reload function and read the file into a variable, and set it's value into the textbox

qt c++ QDialog open new file

After almost a week of searching and reading qt documentation, I still can't figure out how to use QDialog to create a NEW file on my hard disk for writing data. I can open a file and write data if the file already exists, but if I attempt to create a NEW file, I get a message that the file does not exist. I can create a new file if I do not use QDialog by hard coding the path and file name, but would like to be able to choose the file location, and get the customary messages; for instance that the file already exists and asked if it is OK to overwrite it. Here is a snippet of my latest attempt:
void MainWindow::on_pushButton_3_clicked()
{
QString filename = QFileDialog::getOpenFileName(
this,
tr("Sensor data"),
"C//",
"Text File (*.txt)"
);
QFile file(filename);
if (!file.open(QIODevice::ReadWrite))
{
QMessageBox::information(0,"info",file.errorString());
return;
}
QTextStream out(&file);
out<<"string1";
out<<"\n";
out<<"string2";
out<<"\n";
out<<"string3";
out<<"\n";
out<<"string4";
out<<"\n";
out<<"string5";
file.close();
}
Can QDialog be used for this purpose? If not, please point me to information on how it is done.
Thanks in advance!
I think you should use getSaveFileName instead
In Qt exemples there is project called SDI , content simple window and menu and all what you need about file : new, open, save, and save as .

store input of line edit to string qt

I'm a beginner.I am making a simple gui program using qt in which you enter a url/website and that program will open that webpage in chrome.I used line edit in which user enters url and i used returnPressed() slot, but the problem is (it might sound stupid) that i don't know how to take the input by user and store it in a string so that i can pass that string as parameter to chrome.Is im asking something wrong.also tell me how can i save input to a txt file, i know how to do that in a console program.Is this process is same with others like text edit etc.
My mainwindow.cpp:
QString exeloc = "F:\\Users\\Amol-2\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe";
void MainWindow::on_site_returnPressed()
{
QString site;
getwchar(site);
QString space=" ";
QString result = exeloc + space + site;
QProcess::execute(result);
}
What im doing wrong.
thanks
You've got your approach slightly wrong, I can see where you're coming from though. It's actually a lot more simple than you're trying, Qt has a QDesktopServices class that allows you to interact with various system items, including open urls in the browser. There's documentation on it here.
QLineEdit has a text() function that will return a QString. So you can do something like this:
QString site = ui->site->text();
You don't have to use QProcess to open a web site in a browser. You can use QDesktopServices::openUrl static function.
Like this:
QString site = ui->site->text();
QUrl url(site);
QDesktopServices::openUrl(url);
Remember to include QDesktopServices and QUrl headers:
#include <QDesktopServices>
#include <QUrl>