How to pass QString variable to QFile? - qt

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);
...
}

Related

How to wait for Async lamda function to finish before returning value in a QT Web Assembly

so I wrote a programm for my thesis in Qt and now i am supposed to turn it into a working web assembly, which wasnt a real problem except for the filedownload part. I rewrote my filedownload method from:
QString costumfile::read(QString filename){
QString fileName = QFileDialog::getOpenFileName(nullptr, filename, "", "Text Files (*.txt )");
QFile file(filename);
qDebug()<<filename<<"filename";
if(!file.open(QFile::ReadOnly |
QFile::Text))
{
qDebug() << " Could not open the file for reading";
return "";
}
QTextStream in(&file);
QString myText = in.readAll();
//qDebug() << myText;
file.close();
return myText;
}
To this:
QString costumfile::read(QString filename)
{
QMessageBox msgBox;
QString textUser="Open" + filename;
msgBox.setText(textUser);
msgBox.exec();
QString text="hallo";
qDebug()<<filename;
auto fileContentReady = [&](const QString &fileName, const QString &fileContent) {
if (fileName.isEmpty()) {
msgBox.setText("Error");
msgBox.exec();
} else {
text=fileContent;
qDebug()<<text<<"texstis";
return fileContent;
}
return fileContent;
};
QFileDialog::getOpenFileContent(".txt", fileContentReady);
}
and the problem is that the return doesnt wait for the lambda function because its asynch...
I then tried using eventloops which works fine in the Destop applikation but isnt supported in the webassembly Applikation.
So does someone have a good idea how to wait for the fileContentReady Function?
As far as I know, Qt for WebAssembly currently does not support waiting using event loops (at least Qt 6.2 does not). See Qt wiki:
"Nested event loops are not supported. Applications should not call e.g. QDialog::exec() or create a new QEventLoop object."
https://wiki.qt.io/Qt_for_WebAssembly
So you would have to modify your method to handle the asynchronous call. What I mean is that whatever you want to do with the file, you can write directly into the fileContentReady lambda you have. If this is a generic function, you can let the caller register a done callback to execute when the file is ready. Something like:
QString costumfile::read(QString filename,
const std::function<void(const QString&)>& done)
{
...
auto fileContentReady = [=](const QString &fileName, const QString &fileContent) {
if (fileName.isEmpty()) {
// Report error
} else {
text=fileContent;
qDebug()<<text<<"texstis";
done(text);
}
};
QFileDialog::getOpenFileContent(".txt", fileContentReady);
}
// When calling costumfile::read
read(filename, [=] (const QString& text) {
// Do something with `text`
});
Also, about the usage of QMessageBox exec(). This can also cause problems as it internally creates a nested event loop which is not yet supported in Qt for WebAssembly. Instead use the show() method.
auto msgBox = new QMessageBox();
msgBox->setText(textUser);
connect(msgBox, &QMessageBox::finished, &QMessageBox::deleteLater);
msgBox->show();

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.

Construct QString from QJsonArray in Qt

While trying to construct a QString from values from a QJsonArray, I get the following error:
error: passing 'const QString' as 'this' argument discards qualifiers [-fpermissive].
Dunno where I am getting it wrong in this code:
QString <CLASS_NAME>::getData(QString callerValue) {
QString BASE_URL = "<URL>";
QString stringToReturn = "";
QObject::connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply *reply) {
QByteArray barr = reply->readAll();
QJsonParseError jpe;
QJsonDocument jdoc = QJsonDocument::fromJson(barr, &jpe);
QJsonArray synonymsArray = jdoc.array();
foreach (const QJsonValue &jv, synonymsArray) {
QJsonObject jo = jv.toObject();
QString s = jo.value("<VALUE>").toString();
stringToReturn.append(s + ", "); /* ERROR: The error above is from this line... */
}
}
);
request.setUrl(QUrl(BASE_URL + callerValue));
manager->get(request);
return stringToReturn;
}
This is another classic "I wish the world was synchronous" problem. You can't code that way. The getData method can't be written the way you want it to be. getData done that way would block, and that's quite wasteful and can lead to interesting problems - not the last of which is horrible UX.
Depending on your application, there would be several possible fixes:
redo getData in implicit continuation-passing style using coroutines and co_yield - this is the future and can be done only on the most recent compilers unless you use hacks such boost coroutines.
redo getData in explicit continuation-passing style,
redo getData in lazy style with notification when data is available,
have an explicit state machine that deals with progress of your code.
The continuation-passing style requires the least changes. Note the other fixes too - most notably that you shouldn't be using the QNetworkAccessManager's signals: you're interested only in results to this one query, not every query! Catching QNetworkAccessManager::finished signal is only useful if you truly have a central point where all or at least most frequent requests can be handled. In such a case, it's a sensible optimization: there is overhead of several mallocs to adding the first connection to a hiterto connection-free object.
void Class::getData(const QString &urlSuffix, std::function<void(const QString &)> cont) {
auto const urlString = QStringLiteral("URL%1").arg(urlSuffix);
QNetworkRequest request(QUrl(urlString));
auto *reply = m_manager.get(request);
QObject::connect(reply, &QNetworkReply::finished, this, [=]{
QString result;
auto data = reply->readAll();
QJsonParseError jpe;
auto jdoc = QJsonDocument::fromJson(data, &jpe);
auto const synonyms = jdoc.array();
for (auto &value : synonyms) {
auto object = value.toObject();
auto s = object.value("<VALUE">).toString();
if (!result.isEmpty())
result.append(QLatin1String(", "))
result.append(s);
}
reply->deleteLater();
cont(result);
});
}
The lazy style requires the code that uses getData to be restartable, and allows continuation-passing as well, as long as the continuation is connected to the signal:
class Class : public QObject {
Q_OBJECT
QString m_cachedData;
QNetworkAccessManager m_manager{this};
Q_SIGNAL void dataAvailable(const QString &);
...
};
QString Class::getData(const QString &urlSuffix) {
if (!m_cachedData.isEmpty())
return m_cachedData;
auto const urlString = QStringLiteral("URL%1").arg(urlSuffix);
QNetworkRequest request(QUrl(urlString));
auto *reply = m_manager.get(request);
QObject::connect(reply, &QNetworkReply::finished, this, [=]{
m_cachedData.clear();
auto data = reply->readAll();
QJsonParseError jpe;
auto jdoc = QJsonDocument::fromJson(data, &jpe);
auto const synonyms = jdoc.array();
for (auto &value : synonyms) {
auto object = value.toObject();
auto s = object.value("<VALUE">).toString();
if (!m_cachedData.isEmpty())
m_cachedData.append(QLatin1String(", "))
m_cachedData.append(s);
}
reply->deleteLater();
emit dataAvailable(m_cachedData);
});
return {};
}
The state machine formalizes the state progression:
class Class : public QObject {
Q_OBJECT
QStateMachine m_sm{this};
QNetworkAccessManager m_manager{this};
QPointer<QNetworkReply> m_reply;
QState s_idle{&m_sm}, s_busy{&m_sm}, s_done{&m_sm};
Q_SIGNAL void to_busy();
void getData(const QString &);
...
};
Class::Class(QObject * parent) : QObject(parent) {
m_sm.setInitialState(&s_idle);
s_idle.addTransition(this, &Class::to_busy, &s_busy);
s_done.addTransition(&s_idle);
m_sm.start();
}
void Class::getData(const QString &urlSuffix) {
static char const kInit[] = "initialized";
auto const urlString = QStringLiteral("URL%1").arg(urlSuffix);
QNetworkRequest request(QUrl(urlString));
m_reply = m_manager.get(request);
s_busy.addTransition(reply, &QNetworkReply::finished, &s_done);
to_busy();
if (!s_done.property(kInit).toBool()) {
QObject::connect(&s_done, &QState::entered, this, [=]{
QString result;
auto data = m_reply->readAll();
QJsonParseError jpe;
auto jdoc = QJsonDocument::fromJson(data, &jpe);
auto const synonyms = jdoc.array();
for (auto &value : synonyms) {
auto object = value.toObject();
auto s = object.value("<VALUE">).toString();
if (!result.isEmpty())
result.append(QLatin1String(", "))
result.append(s);
}
m_reply->deleteLater();
});
s_done.setProperty(kInit, true);
}
}
Of course it would be wrong: stringToReturn is declared as a local variable in getData, It would be const if you use [=] and it will die at time of function object's call - by finished signal , if captured by reference. Lambda expression will have a dangling reference in it.That's bad place to put variable that serves as output for this function object, that variable stops to exist on return from getData.
Function object created by lambda expression here is called after getData returned. it would be called sometime when signal is fired as a result of sent request, it's an asynchronous handler. getData IS NOT the caller of lambda in this case. Caller of lambda is signal-slot system. provided that getData doesn't call lambda explicitly, we have no guarantee that function object is returned before lifespan of local storage had come to end.
Possible remebdy here is to use a field of this, if you can guarantee that this ( <CLASS_NAME> instance) is still "alive" when finished() is fired. essentially this "getData" is unable to return that value unless you would pause it until request is done (which defeats asyncronous approach).
In fact, finished would be fired when QNetworkReply::finished would be fired, QNetworkAccessManager::get just post request and returns said reply immediately. Signal is fired when you receive data (readyRead is emitted)

QT4 > QT5 for QDesktopServices::storageLocation

I am trying to convert the following code to a QT5 version:
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
But sadly I am getting the following error:
error: no member named 'storageLocation' in 'QDesktopServices'
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
~~~~~~~~~~~~~~~~~~^
and
error: no member named 'DocumentsLocation' in 'QDesktopServices'
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
~~~~~~~~~~~~~~~~~~^
Since Qt 5, storageLocation() and displayName() methods of QDesktopServices are replaced by functionality provided by the QStandardPaths class, so your myDir can be assigned like this:
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);

using getOpenFileName in a handler

I have implemented the getOPenFileName in a handler in qt (in a when_pushbutton_clicked more specifically). How can I save the produced string in a QString in main rather than inside the handler?
You can use a signal connection to save in a QString variable the path of your file name.
const QString fileName = QFileDialog::getOpenFileName(0, tr("Select the file"), getLastDirectory(), "Txt Files (*.txt)");
if (fileName.isEmpty()) {
// No file was selected
return;
}
// then emit the signal
emit fileWasSelected(fileName);
In your main function you cant handle the event in the main class by a simple connection:
QObject::connect(yourClass, &YourClass::fileWasSelected, [&](const QString& filename) {
// Now, do what you want with your path
}):
Another way, its to save the file in a private variable, and set up a getter:
class MyClass {
....
public:
inline QString path() const { return _path; }
private:
QString _path;
}
And then access to the variable from the main.

Resources