Qt: Simple Example for Quazip - qt

I built the quazip library. I need a simple example that shows how to unzip a zip File. For example.
Quazip zipFile( QFile("test.zip") );
zipFile.unzip();
Tests shown in quazip is little bit confusing. I searched for a brief amount of time to find an example and I wasn't able to find one.

Here is a quick example showing how to read the files. You will need to make some modifications to the code in the loop to write the data to a file or perform whatever operations your application requires:
QuaZip zip("zipFile.zip");
zip.open(QuaZip::mdUnzip);
QuaZipFile file(&zip);
for(bool f=zip.goToFirstFile(); f; f=zip.goToNextFile()) {
file.open(QIODevice::ReadOnly);
//same functionality as QIODevice::readData() -- data is a char*, maxSize is qint64
file.readData(data,maxSize);
//do something with the data
file.close();
}
zip.close();

You can use static functions of the class JlCompress. It's very easy to use.
Static Public Member Functions
static bool compressFile (QString fileCompressed, QString file)
static bool compressFiles (QString fileCompressed, QStringList files)
static bool compressDir (QString fileCompressed, QString dir=QString(), bool recursive=true)
static QString extractFile (QString fileCompressed, QString fileName, QString fileDest=QString())
static QStringList extractFiles (QString fileCompressed, QStringList files, QString dir=QString())
static QStringList extractDir (QString fileCompressed, QString dir=QString())
static QStringList getFileList (QString fileCompressed)
Source: http://quazip.sourceforge.net/classJlCompress.html

Related

Converting QMap<QString, QString> to Json string results empty

I have a function defined and used as this:
// usage:
QMap<QString, QString> map = ...;
foo(map);
// defination:
QString stringMapToJson(const QMap<QString, QString>& arg) {
QVariant v = QVariant::fromValue(arg);
JsonDocument doc = QJsonDocument::fromVariant(v);
...
}
Then I realized v is empty.
Is there a method to convert QMap<String, QString> to QMap<String, QVariant>, so above v could be valid?
Why above v is empty? I read people were saying QVariant and qMetaData, I don't understand given the following valid, why QString have a qMetaData problem:
QString s = "";
QVariant v = s;
(A Java programmer starts her pleasant C++ journey.)
Thanks.
There are 2 ways to do this. The first is to convert your map to a QMap<QString, QVariant> like you mentioned:
QByteArray stringMapToJson1(const QMap<QString, QString>& arg)
{
QVariantMap vmap;
for(auto it = arg.cbegin(); it != arg.cend(); ++it)
{
vmap.insert(it.key(), it.value());
}
const QVariant v = QVariant::fromValue(vmap);
const QJsonDocument doc = QJsonDocument::fromVariant(v);
return doc.toJson();
}
Alternatively, you can build the json object directly from the map. In this case it's the same amount of code:
QByteArray stringMapToJson2(const QMap<QString, QString>& arg)
{
QJsonObject jObj;
for(auto it = arg.cbegin(); it != arg.cend(); ++it)
{
jObj.insert(it.key(), it.value());
}
QJsonDocument doc;
doc.setObject(jObj);
return doc.toJson();
}
This seems like a stylistic choice and I am unsure which would be faster. Both produce the same output.
One thing to note: The conversion from QString to QVariant is predefined in Qt, so the first method works fine. For objects of your own classes you would have to register that type and provide a suitable conversion which can be a bit tough to get right. In the second method you could do this conversion inline in the loop.

How to load QTranslator from database?

There is no way to load QTranslator from my own way.
I want to exclude .ts files from architecture of my app. I just want to load my languages from databse, whitch will be update from anywhere. And i don't want to load any files(.ts). Does exists the way somthing like this:
QTranslator::load(QStringList)??? QStringList is a language pairs.
The QTranslator::translate method is virtual - which means you can simply create your own translator that extends QTranslator and override this (and one other) method:
class MyTranslator : public QTranslator
{
public:
MyTranslator(QStringList data, QObject* parent) :
QTranslator(parent)
{
// ...
}
bool isEmpty() const override {
return false; //or use your own logic to determine if data contains translations
}
QString translate(const char *context, const char *sourceText, const char *disambiguation = nullptr, int n = -1) const override {
// Use the data to somehow find your translation
}
};
I understand your goal. Why don't you get the data from your database, save it as temporary file, load via QTranslator (regular way), then delete the temporary file?
Another option is maybe the overload for:
bool QTranslator::load(const uchar *data, int len, const QString
&directory = QString())
(from: http://doc.qt.io/qt-5/qtranslator.html#load-2 ), which would allow you to load from your own structure without temp file.

Transmit QMap by QMimeData

Is any ideas how i can transmit QMap<QString, QString> in Drag and Drop mode by using QMimeData?
Now i convert QMap into QString like this:
"key1:value1;key2:value2;...keyN:valueN" and assigned it to QMimeData::setText().
Then on dropEvent() i rebuild QMap from QString. Is this right way?
Convert QString to QMap
...
QStringList splittedParams = params.split(";");
QMap<QString, QString> *map = new QMap<QString, QString>();
foreach(QString param, splittedParams)
{
if(param.isEmpty()) continue;
QStringList str = param.split(":");
map->insert(str[0], str[1]);
}
...
That's going to fall apart if your strings contain the separators. For a more robust approach use something like
QByteArray ba;
QDataStream ds(&ba, QIODevice::WriteOnly);
map >> ds;
mimeData->setData(QStringLiteral("your/mime/type"), ba);

How to pass QString variable to QFile?

getData gets the chosen file from a QTreeView and displays it on label 'test', enables the 'Apply' button, which when clicked calls setTheme
void OptionsDialog::getData(const QModelIndex &index)
{
QString selected = model2->filePath(index);
ui->test->setText(selected);
ui->pushButton_apply_theme->setEnabled(true);
}
void OptionsDialog::setTheme()
{
//char *file = selected->toLatin1().data();
//const std::string file = selected->toStdString();
QFile qss(selected);
qss.open(QFile::ReadOnly);
qApp->setStyleSheet(qss.readAll());
qss.close();
}
I can't seem to pass the filePath to QFile in the format it wants, commented lines are some attempts which failed. ' char *file = selected->toLatin1().data();' compiles but segfaults in use.
As is it fails with:
qt/optionsdialog.cpp: In member function ‘void OptionsDialog::setTheme()’:
qt/optionsdialog.cpp:176:23: error: no matching function for call to ‘QFile::QFile(QString*&)’
QFile qss(selected);
Forgive me for I am used to python, this is driving me nuts, any help appreciated!
QString selected = model2->filePath(index); does not set the variable in the (maybe same named) member OptionsDialog::selected. This creates a new local variable.
If you have a member variable called selected then you should use it like this:
void OptionsDialog::getData(const QModelIndex &index)
{
selected = model2->filePath(index);
...
}

QSettings value method returns wrong QString

I have ordinrary text file with settings, which is generated by java application. Inside this file, there is a key db.url, which has value db.URL=jdbc\:mysql\://192.168.0.101\:3306/dbuser. I parse this file with QSettings class in QSettings::Native mode, everything is ok, but this db.URL gets messed up if I read it via value() method. Whatever I do (if I transform it into QString or QUrl), I get same result: jdbcmysql//192.,168.0.1013306/user. Why this key gets messed up?? I am using Qt 5.4 on Kubuntu 14.10 with kernel Linux desktop001 3.16.0-30-generic #40-Ubuntu SMP Mon Jan 12 22:06:37 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux. Here is a simple method that wrongly reads value of key:
QString UePOSSesttings::ueReadDbUrl() const
{
// QVariant dbUrl=this->value(UeDefaults::UeDbKeys::KEY_DB_URL);
return this->value(UeDefaults::UeDbKeys::KEY_DB_URL).toString();
}
and constants:
#ifndef UEDEFAULTS
#define UEDEFAULTS
#include <QString>
namespace UeDefaults
{
namespace UeDbKeys
{
static const QString KEY_DB_DRIVER="db.driver";
static const QString KEY_DB_PASSWORD="db.password";
static const QString KEY_DB_URL="db.URL";
static const QString KEY_DB_DRIVER_LIB="db.driverlib";
static const QString KEY_DB_ENGINE="db.engine";
static const QString KEY_DB_USER="db.user";
}
}
#endif // UEDEFAULTS
QSettings clears up the string from unsupported escape sequences, in this case \:. Remove \ slashes before reading the value or don't use QSettings for parsing unsupported file formats.
Perhaps not the most optimal solution but you could processes the settings file to escape all \: before reading it with QSettings.
QFile oldSettings("settings.txt");
oldSettings.open(QIODevice::ReadOnly);
QString data = QString::fromAscii(oldSettings.readAll().constData());
oldSettings.close();
data.replace("\\:", "\\\\:");
QFile newSettings("/tmp/settings.txt");
newSettings.open(QIODevice::WriteOnly);
newSettings.write(data.toAscii(), data.size());
newSettings.close();
I did it:
void UePOSSesttings::ueParseData(const QString& filename)
{
QFile settingsFile(filename);
QString data;
settingsFile.open(QIODevice::ReadOnly);
data=QString::fromLatin1(settingsFile.readAll().constData());
data.replace("\\:",
":");
this->ueSetParsedData(data);
qDebug() << this->ueParsedData();
settingsFile.close();
}
and now I get this url:
db.URL=jdbc:mysql://192.168.0.101:3306/dbuser
which is ok!

Resources