File Not Being Created in QT C++ using QFileDialog - c++

there I'm trying to make a simple notepad application. I've got a new file menu item. When the user clicks on that, it checks whether the text field is empty or not. If that is not empty then it prompts to save the work. If the user opts for yes then it asks for the location using QFileDialog. However, this code doesn't create the file at the provided destination. Can anyone figure out this code?
if(this->checkTextField()==false){ //checkks whether the textField is empty or not
QMessageBox::StandardButton reply = QMessageBox::question(this,this->appName,this->document_modified);
if(reply == QMessageBox::Yes){
QString filename = QFileDialog::getSaveFileName(this,"Save the File",QDir::homePath(),this->textFilter);
QFile file(filename);
QTextStream out(&file);
QString text = ui->textEdit->toPlainText();
out << text;
file.flush();
file.close();
}
}

Simply creating a QFile will neither create nor open a file on the filesystem. You have to open it to write something to it/read from it.

Related

How do i load a textfile to QListwidget and also save it back

How do i load a text file into QListWidget , such that each line in the textfile is an item in QListWidget,
and once i populate it, i also want to save all items of listwidget into a text file , such that each item of listwidget is in a line in the text file , to accomplish that i am attempting this
QString temp;
for(int i=0; i< ui->mylistwidget->count();i++)
{
QListWidgetItem* item = ui->mylistwidget->item(i);
temp += item->text();
}
std::string total_script = temp.toStdString();
i got all the text of listwidget items in a string , what do i do next if i want to save it in a text file?
and also how do i load text file and populate my qlistwidget with items ?
Qt provides QFile and QSaveFile classes for convenient file input/output operations. QSaveFile is special in as it will only (over)write the destination file when you commit it. For both parsing and writing the file contents, you can use QTextStream, which exposes the file contents as a stream you can read from or write to, including conversion of various variable types.
For importing from file:
Use a QFile to open the file
Construct QTextStream with the file as argument
Use QTextStream::readLine() in a while-loop to read lines and create items
For exporting to file:
Use a QSaveFile, again construct QTextStream on the file
In your loop, use QTextStream::operator<< to append the item text to the stream
Call commit() on the file so it is written
Example without the loop:
QSaveFile fileOut(filename);
QTextStream out(&fileOut);
out << "Qt rocks!" << Qt::endl; // do this for every item
fileOut.commit()

QIODevice::read(QFile, path): device not open

I'm new in qt, I'm trying to read a text file and put it into a text browser. I created the button and the text browser, when I clicked the button I want that the content of the file is put into the text browser. This is the method used on the mainwindow:
void MainWindow::on_pushButton_clicked() {
QFile file(C:\\Users\\branda\\Desktop\\Tools.txt");
if(!file.open(QIODevice::ReadOnly))
QMessageBox::information(0, "info", file.errorString());
QTextStream in(&file);
ui->textBrowser->setText(in.readAll()); }
The error message: "QIODevice::read (QFile, "??C:\Users\branda\Desktop\Tools.txt"): device not open".
The message box says: "The file name, directory name or volume label syntax incorrect".
Which is not, because I copied the path from the file property.
The main.cpp file is still the same as when it was created.
You miss a " at the begining of the dir string;
QFile file(C:\\Users\\branda\\Desktop\\Tools.txt");
Try this:
QFile file("C:/Users/branda/Desktop/Tools.txt");

Getting the name and location of selected file Qt

I have a program in which I have a button to get File Dialog like
How can I select a file, get the file name and location, and save that to a string displayed in the ui.The signalclicked(), emitted from the button, is connected to the slot fileSELECT().
........
void MainThread::fileSELECT(){
QString fileName = QFileDialog::getOpenFileName(this,tr("Select video"),"d:\\BMDvideos",tr("Video files (*.avi)"));
}
so when I select an .avi file, how do I get its location in fileName displayed like
d:\BMDvideo\videFile.avi
so I thinks that I got it now. my first code was completly wrong.
void MainThread::fileSelect(){
QString fileName = QFileDialog::getOpenFileName(this,tr("Select video"),"d:\\BMDvideos",tr("Video files (*.avi)"));
QLabel *testLabel = new QLabel(fileName);
BOX->addWidget(testLabel);
}
I can see now the path of the selected file
To get the folder path, you can use QFileDialog::getExistingDirectory, and to get the file-name use QFileDialog::getOpenFileName

File Input - File not being read QT

I'm very new to C++ and QT. Basically, I just done Java stuff, but we're being thrown in C++ for a module, in which we have to design a Zork game UI. The way I am planning to create the Room object is have the Room constructed with a roomnum.long, .short and .name for the long desc, short desc and name.
For the first room, I'm just going to load the file directly for the moment until I get onto objects etc properly. However, I can't seem to get the file written into a text label. The return "restart game etc" does get written on button press, but not the contents of the file. The Rooms folder is in the same folder as the source file (islandmain.cpp in this case)
Any ideas?
void TheIslandMain::on_startButton_clicked()
{
ui->roomDesc->setText(readFirstRoom("/Rooms/room1.long"));
ui->roomDesc->setWordWrap(true);
}
QString TheIslandMain::readFirstRoom(QString filename)
{
QFile mFile(filename);
if (!mFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "Could not open file for reading Line 31";
return "Could not load file. Please restart game.";
}
QTextStream in(&mFile);
QString fileInput = in.readAll();
qDebug() << fileInput;
mFile.close();
return fileInput;
}
check if the file exists using bool QFile::exists(const QString& path) and also if its only the filename you have in your function or the whole path (path is needed)
soo long zai
/Rooms/room1.long points to a file in root, then Rooms, then room1.long as the file. If Rooms is the directory it needs to be relative to the application itself, so if Rooms is in the same directory as your application it'd just be Rooms/room1.long, if it's in a higher level ../Rooms/room1.long or Resources/Rooms/room1.long.

Importing the entries to be filled in the UI, from a file, in qt4

I created a UI in qt4. Now I should be giving an option to the user to fill the entries in the UI, from an existing file on system,which the user can browse for.
Now, Iam able to set the line edit entries in my UI from the file that the user specifies but I am not able to set the highlighted text in the comboboxes to what the file has. This might be very vague, Iam not able to explain this properly.Here is the code snippet i used:
//browsing for the file
path = QFileDialog::getOpenFileName(
this,
"Choose a file to import data from",
QString::null);
QFileInfo fi(path);
ui->lineEdit_21->setText( path );
//opening the file specified by user, for reading
name = fi.fileName();
dir = fi.path();
QDir::setCurrent(dir);
QFile read(name);
QString str;
if (!read.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&read);
while (!in.atEnd())
{
QString line = in.readLine();
//filling the UI from the file
if(line.contains("AP SSID :", Qt::CaseInsensitive))
{
str = line.section(':', 1, 1);
ui -> lineEdit->setText(str);
}
}
This works fine but now how do I change the selected entry in a combobox, in accordance with the file?
if(line.contains("FREQUENCY :", Qt::CaseInsensitive))
{
str = line.section(':', 1, 1);
ui -> comboBox_2->setEditText(str);
}
I tried this but this is not working. My combobox_2 has two frequencies 2.4GHz and 5GHz. If the user selected file has 2.4GHz then I want the combobox to update itself such that 2.4GHz entry is highlighted. Hope I have made my point. Please help.
Thanks
You have to use the findText function in order to get the index of the given text in the combobox.
int frequencyIndex = ui->comboBox_2->findText(str);
if (frequnecyIndex != -1)
ui->comboBox_2->setCurrentIndex(frequencyIndex);