How to open file in Qt application? - qt

I wrote a notepad in qt gui, but when I associate a file with it and click on it, the .exe is run and file is not opened, so I have to open it using
QFileDialog::getSaveFileName(
this,"Save As","",
"Text Document (*.txt)\n All Files (*.*)")
When we click on text.txt it directly opens the file in notepad. How can I make same for my app?
remark: QDir::currentpath() returns the path of file.txtq (which is associated with it) on which we clicked but I was not able to return its name.

When double-clicking the file (associated with your exe), its path is passed to your program via command line arguments. You can access them in the following way:
if (QApplication::arguments().size() > 1) {
const QString filename = QApplication::arguments().at(1);
// "filename" now contains path and name of the file to open.
}
Also, I have no idea why you are using QFileDialog::getSaveFileName(). In order to call the open file dialog, you'll need the QDialog::getOpenFileName() method.

Related

QT How Keep the previous user selected image path in memory for instant loading using QFileDialog

I am working on a program that takes a file from a directory and when I again try to select the path it will not show the same directory. So, I need to fix the previous path when I choose the next path it will select the previous path.
The first time I will select this path
Example:- C:\Work\Projects\GDCM\gdcm-2.8.6
Next time I will again click to take a file from the same path but it will show the by default path.
Example:- C:\Program Files (x86)
I am using QFileDialog for selecting the path:-
QString dir = "";
QFileDialog dia;
dir = dia.getExistingDirectory(this, tr("Select DICOM Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
dia.setDirectory(dir);
The third parameter of QFileDialog::getExistingDirectory specifies the initial directory used by the dialog, and you are not using it correctly.
You are clearly using Windows yet you are always setting the initial directory to a unix home directory /home. Rather initialise your string variable and reuse it in subsequent calls.
QFileDialog dia;
dir = dia.getExistingDirectory(this, tr("Select DICOM Directory"), dir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
Store the return value of dir and reuse it the next time you invoke the dialog for the third parameter. You don't need to be using setDirectory.

GUI made using JavaFx that uses File Input/Outstream - Can it be exported as JAR and open .txt file?

I am trying to export a GUI (Student Grade Manager App) I created in eclipse as a JAR file and run it on my desktop. Nothing happens when I double click it (though it does successfully export) at the moment. Here's an screenshot:
GUI Screenshot - Click here
I'm assuming the main issue here is that in my GUI, I am using the File Input stream in the CourseSectionApp.java file (Where the main method is located). It reads a .txt file called "StudentMarks.txt" and that's where it gets all its student data from.:
BufferedReader aFile = new BufferedReader ( new FileReader("Marks.txt"));
model = CourseSection.loadFrom(aFile);
Is there anyway to get this to work? Can I have the .txt file just export with the JAR file so it loads together? OR is there a way to put a sub-window, like modern applications have where the user can go to File->New-> and say, "load from file", and then be allowed to navigate to the .txt file on his computer?
My main goal is to be able to email this to friends and have them use it, but I googled around and only found a few people having similiar issues with not-so-clear answers. And if the JAR file cannot do this, what can? Will making it a .exe change anything?
Screenshot of Marks.txt file
I tried to make this question as legible as possible and if there is any other information I can provide you guys, please let know.
If you don't need to write to the file, including the file as resource in the jar would be your best option. This way you can always be sure the file is available via jar entry name. E.g.
try (InputStream is = getClass().getResourceAsStream("/data/Marks.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)){
model = CourseSection.loadFrom(br);
}
If you also need to write to the file, you can use FileChooser to open a dialog for choosing a file:
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Marks File");
fileChooser.getExtensionFilters().add(new ExtensionFilter("Text Files", "*.txt"));
File file = fileChooser.showOpenDialog(null); // you could also pass a owner window here
if (file != null) {
// TODO: handle completed file selection by user
}
The issue described in the comments indicates that there is a problem with the classpath though. You need to make sure all required classes are available when the application is run...

Qt - Add files to project

I'm making an application part of which is reading from an XML which stores some preferences. However, whenever I build the project, all the sources get copied but the preferences file does not! I have added the following to the .pro file -
RESOURCES += rsc.qrc
And my rsc.qrc contains
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>data/preferences.xml</file>
<file>data/gamedata.xml</file>
</qresource>
</RCC>
Now whenever I try to open preferences.xml
QFile preferences(":/data/preferences.xml");
if(!preferences.exists()){
preferences.open(QFile::WriteOnly);
preferences.write("abc");
qDebug() << "Written";
}
else {
qDebug() << "File exists";
}
Absolutely nothing gets printed and even the rest of the application stops working.
You don't use the resource part correctly in your example.
It will most likely not work because you try to write to a resource that is embedded into your executable after you have build your application. Reading is fine, but writing can't work by definition.
If you want a editable setting files, you have to distribute them along with your executable, or use a different method for reading/writing your settings like QSettings.
However using QSettings also means, that you will need to configure all your default settings in your loading function in case the values do not exist if you use the default configuration. Meaning you use registry on windows.
You have the option to force the use of a INI file format in the constructor of QSettings, this can make sense if you want to provide a default settings INI file instead of your xml files.
In case you want to store more complex data a xml file might be needed anyway, so if you want to stick with that you will need a way to copy your setting files to your build path. This can be done within your pro file with QMAKE_POST_LINK.
Example:
COPY_CMD = "$$PWD\\data\\preferences.xml $$OUT_PWD\\release\\data\\preferences.xml"
COPY_CMD = $${QMAKE_COPY} $$replace( COPY_CMD, "/", "\\" ) $$escape_expand( \\n\\t )
QMAKE_POST_LINK += $$COPY_CMD

Make a text file for Qt

I can make a file and make my Qt project read and write to it .
But How can I make it create it's own text file for the first time then it writes and reads from and to it later for example i want it to write and read to and from this directory C:\Users\Administrator\Documents .
I will answer supposing that you are asking (don't know if I understood well, since your question is hardly understandable) how to create a file one time, then later, write and read from this file already created.
First, you have to give your file a name.
QString fileName = "C:\Users\Administrator\Documents\file.txt";
QFile file(fileName);
If your file is not already created : calling the function QFile::open(OpenMode mode) will create this file :
bool openOk = file.open(QIODevice::ReadWrite);
if (openOk)
{
// process
}
You can now write and read from your file.
Later, if you want to use your file again, just call this function again : if the file is already created, then you can read/write in this file.

Batch file write to txt

I want to make a batch file that will ask user for input, than write that input to a specific position in an already written txt file(called commands.txt which contains query) and call sqlite3 < commands.txt
I need this so inside the commands.txt where the query is, in LIKE 'userinput' i will add the users choice (parameter)
Although your question is not really specific enough and verging on the kind of inappropriate question that for stackoverflow (it does not include code), as hinted at by the comment, I'll take it at face value and assume there is much you need help with.
First let me deal with the question "I need to make a batch file"
A batch file is a simple text file with the extension .bat. You can create it with a text editor like notepad. We do not know what kind of system you have (Windows, linux, Mac etc) but lets assume Windows as you asked for a batch file. We do not know which version of windows (7 or 8 etc), So I'll try and be generic.
All windows machines come with a simpe text file editor called notepad. You can open this by typing notepad into the search box on windows 7 or 8. Lets start with a simple batch file:
:: This is a batch file
#echo off
echo Hello World
exit /b
Type (or paste) those 4 lines into notepad. Now select the file menu and select Save As, now in the Save As Type: selector choose All Files. In the File name: box type the desired name with the bat extension, such as doit.bat. Ensure you choose a suitable directory to place your new batch file. Leave the encoding as ASCII. Click Save. You have now made your first batch file.
Now you need to execute that batch file. Using the Windows File Explorer find the folder where you saved that batch file. While viewing the folder, hold down the shift key on the keyboard and then right click in the background of the folder and select Open Command window here. You will now have a command prompt window. You can now execute your new batch file by typing its name doit. It will display:
Hello World
OK - Now you have created your first working batch file.
Now for the next part; Asking the user for input. This is done with the set /p command. Add this to your batch file (before the exit line):
Set /P Like="Give me your input: "
echo Your input was: %Like%
That has solved the second part. Now the third part, edit the commands.txt file. If you do an internet search for a similar problem (editing files in batch files) you might find this help page: http://www.ousob.com/ng/edlin/ng96d9.php. This shows a generic way of changing any text string to any other in a file using EDLIN from a batch file; unfortunately EDLIN (and EDIT) are no longer included in windows so these batch files are not much help.
A search of stackoverflow finds similar queries which contain an answer for you.
So now you have all the parts of the answer:
How to make a batch file
How to prompt the user for input
How to replace lines of text in the commands.txt
You should be able to put it together and get it to work....

Resources