How to create a new File with full path in Qt? - qt

I am a Qt beginner and just got stuck with the problem. I am looking for a file SomePath/NewDirectoryA/NewFile.kml (NewFile.kml will be the only file in NewDirectoryA, having this directory just to maintain semantics in the project).
If SomePath/NewDirectoryA/NewFile.kml exists then I will use it in my code and if it doesn't exist then I have to create it. If this File doesn't exist then this directory also doesn't exist in SomePath. So If only I have to create a file I can use QFile and open it in ReadWrite or WriteOnly mode.
But the problem is I have to create the file with the directory itself.
I tried with QFile with file name SomePath/NewDirectoryA/NewFile.kml but it didn't worked.
Please suggest me a way in which I can create a new file (NewFile.kml) in a new directory (NewDirectorA) at a given location (SomePath).

bool QFile::open ( OpenMode mode ) [virtual]
[...]
Note: In WriteOnly or ReadWrite mode,
if the relevant file does not already
exist, this function will try to
create a new file before opening it.
Qt's caveat for file creation
Platform Specific Issues
File permissions are handled differently on Unix-like systems and
Windows. In a non writable directory on Unix-like systems, files
cannot be created. This is not always the case on Windows, where, for
instance, the 'My Documents' directory usually is not writable, but it
is still possible to create files in it.
Directories are created with
bool
QDir::mkdir
( const QString & dirName ) const
Creates a sub-directory called
dirName.
and
bool QDir::mkpath
( const QString & dirPath ) const
Creates the directory path dirPath.
The function will create all parent
directories necessary to create the
directory.

AFAIK it is not possible to create the file and the directory directly with QFile. You have to first create the directory (QDir::mkpath will create the full path) and then the file (QFile::open).
QString path("SomePath/NewDirectoryA/");
QDir dir; // Initialize to the desired dir if 'path' is relative
// By default the program's working directory "." is used.
// We create the directory if needed
if (!dir.exists(path))
dir.mkpath(path); // You can check the success if needed
QFile file(path + "NewFile.kml");
file.open(QIODevice::WriteOnly); // Or QIODevice::ReadWrite

Related

QFileDialog:Recursive selecting files for unzip

I want to use 7za.exe as a subprocess in qt application, select a root directory using the browse button, look for all .zip and .7z files and extract their content.
Now with the code I came up
I am unable to recursively select any .zip or .7z in the root folder
and extract them. There is some better way of using the commands (arguments ) in uncompressZipFile().
How can I get the files name, name of the files that has
been extracted from the root folder?
I want to use 7za.exe as a subprocess in qt application, select a root directory using the browse button, look for all .zip and .7z files and extract their content.
Now with the code I came up
I am unable to recursively select any .zip or .7z in the root folder and extract them.
How can I get the files name of the files that has been extracted from the root folder?
void MainWindow::uncompressZipFile()
{
QStringList queryArguments;
queryArguments << "e";
queryArguments << """" + choosenDir + """"+"/*.zip";
queryArguments << "-ro"+choosenDir+"/example";
zipperProcess.setWorkingDirectory(QCoreApplication::applicationDirPath());
qDebug() << zipperProcess.workingDirectory();
qDebug()<<queryArguments;
zipperProcess.start("7za.exe", queryArguments);
}
void MainWindow::on_browseFileButton_clicked()
{
qDebug()<<"browse button clicked";
choosenDir = QFileDialog::getExistingDirectory(this, tr("Choose catalog"), ".", QFileDialog::ReadOnly);
qDebug()<<choosenDir;
ui->path->setText(choosenDir);}

what is absolute path in C++/WinRT

the error: WinRT originate error-0x80070057:'The specified path (msappx:\Local\C:\Windows\Web\Screen\img103.png) is not an absolute path, and relative paths are not allowed. '
when I used C++/WinRT,the function call is
winrt::Windows::Foundation::IAsyncOperationwinrt::Windows::Storage::StorageFile temp = StorageFile::GetFileFromPathAsync(hFilname);
what can I do?
For StorageFile.GetFileFromPathAsync() method, you don't have permission to access the specified file, please see here.
My suggestion is that you could store the image file in Application install directory that app can access, then use the following code to access it.
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string path= Path.Combine(folder.Path, #"Data\img1.png");
StorageFile.GetFileFromPathAsync(path);
Note that the Application install directory is ..ProjectPath\bin\x86\Debug\Appx

QT - Where is config.ini

I wanted to save db's conenction in Config.ini file. I created it and added to project (as "other file") - suitable record appered in .pro file.
I started in code with this:
QSettings settings(QDir::currentPath()+"/"+fileName, QSettings::IniFormat);
Then i created 2 functions
for savng settings:
settings.beginGroup("DB");
settings.setValue("HostName",_hostName);
//_hostName is attribute I can access, so that's not an issue
settings.endGroup();
for reading settings
settings.beginGroup("DBSettings");
_hostName =settings.value("HostName", "Unknown").toString();
// hostName is attribute i can access
settings.endGroup();
I initially called 1. and then 2.
It seems like that the .ini file is created and I could read from it, but it's not that I added to project and i can't find it in the folder it supposed to be.
It works, but I need to include it into the project and I need to be able to "control" it.
I resolved this problem myself. Turned out, that line :
QSettings settings(QDir::currentPath()+"/"+fileName, QSettings::IniFormat);
just has to be repalced with
settings = new QSettings(QDir::currentPath()+"/"+fileName, QSettings::IniFormat);

Qt-application only works correctly if started from the command line

I made a pretty simple application with Qt Creator on Ubuntu 12.04. The application reads an xml-file and shows a couple of images. But when I try to start the application by double clicking the icon on a different machine (running Lubuntu), the images are not shown, and the xml-file is not read. The application does work properly when it is started from the command line by typing ./App.
Why does it behave like this and how do I fix it?
edit: The method that reads the xml:
QDomDocument doc("document");
QString path = "datastorage.xml"; // xml is in same directory as the executable
QFile xmlFile(path);
if (!xmlFile.open(QIODevice::ReadOnly))
throw QString("Error with XML: Could not open file " + path);
if (!doc.setContent(&xmlFile)) {
xmlFile.close();
throw QString("Error with XML: Could not set QDomDocument content from " + path);
}
xmlFile.close();
QDomElement root = doc.documentElement();
return root;
Simply you are using relative paths to read files and those paths are always relative to "working directory". If you're launching your app from console, and all required files are within app directory then everything works. When launching from desktop working directory may be different. Just prepend QCoreApplication::applicationDirPath() to all paths you're using.

QSettings - where is the location of the ini file?

I'm using QSettings to store some data as ini file in Windows.
I want to see the ini file, but I don't know what is the location of the ini file.
This is my code:
QSettings *set = new QSettings(QSettings::IniFormat, QSettings::UserScope, "bbb", "aaa");
set->setValue("size", size());
set->setValue("pos", pos());
Where do I have to look? Or may be I miss the code which write it to the file?
When does the QSettings write its values?
To print out the exact location of your settings file use method fileName method of QSettings class.
QSettings settings("folderName", "fileName");
qDebug() << settings.fileName();
Console output looks then like:
/home/user/.config/folderName/fileName.conf
I think you'll find everything you're looking for here : http://doc.qt.io/archives/qt-4.7/qsettings.html
It's plateform specific, see under :
Platform-Specific Notes
Locations Where Application Settings Are Stored
You can store Settings in files as well :
QSettings settings("/home/petra/misc/myapp.ini",
QSettings::IniFormat);
QSettings save location changes to the QSettings.Scope enum. QSettings save to the Local scope by default. On Linux, I found my local settings in:
~/.config/CompanyName/ApplicationName.conf
If you create a QSettings without giving any specific path, the ini file will be located in the application path.
QSettings Settings("myapp.ini", QSettings::IniFormat);
Settings.setValue("Test", "data");
//...
qDebug() << QApplication::applicationDirPath();
Be careful though : the application path might change : for instance, if you are developping your app with Qt Creator, in debug mode, the application path is in the /debug subfolder.
If you are running it in release mode, the application path is in the /release subfolder.
And when your application is deployed, by default, the application path is in the same folder as the executable (at least for Windows).
Check out the QStandardPaths class, it links to multiple standard paths including configuration on all supported platforms. https://doc.qt.io/qt-5/qstandardpaths.html
QT >= 5.5:
QString path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
QT < 5.5:
QString path = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
There are paths for config files in shared config directories, application data directories, and more.
In linux you can use this snippet or insert this lines into your main code for find location of your file with python.
from PyQt5.QtCore import QSettings
settings = QSettings("Organization Name", "App name")
print(QSettings.fileName(settings))
It should return an output like this.
/$HOME/.config/Organization Name/App name.conf
Source
in windows path is like below:
C:\Users\user_name\AppData\Roaming\bbb
On Mac OSX, I found the file under at ~/Library/Preferences
The QSettings class provides persistent platform-independent application settings.
Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in XML preferences files on Mac OS X. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files
http://doc.qt.io/archives/qt-4.7/qsettings.html
On Windows without providing an ini filename, you'll find the data in the registry.
Using this code snippet:
int red = color.red();
int green = color.green();
int blue = color.blue();
QSettings settings("Joe", "SettingsDemo");
qDebug() << settings.fileName();
settings.beginGroup("ButtonColor");
settings.setValue("button1r", red);
settings.setValue("button1g", green);
settings.setValue("button1b", blue);
settings.endGroup();
After running this code, you'll see the output:
"\\HKEY_CURRENT_USER\\Software\\Joe\\SettingsDemo"
Now, opening the regedit tool and following the path list you got: 1

Resources