String creation of file pathin char format with Qt (VC++) - qt

I want to create a GUI application using Qt. For that I need to get the filename using:
QString fileName=getOpenFileName(.....)
I am using Windows and want to have the filename path in C:\a\b\c format and pass it to a function accepting char variables. How can I implement this?

According to the Qt FAQ
QString path = QFileDialog::getOpenFileName(...);
QByteArray byteArray = path.toLocal8Bit();
const char *charPath = byteArray.data();

Related

Problems in converting to UTF-8 in Qt

I try to show a persian string in Qt:
QMessageBox msg;
QString str = "یا حسین";
msg.setText(QString::fromUtf8(str));
msg.exec();
but it shows the following error :
/home/msi/Desktop/VoMail
Project/Project/VoMail-build-desktop-Qt_4_8_1_in_PATH__System__Release/../VoMail/mainwindow.cpp:40:
error: no matching function for call to 'QString::fromUtf8(QString&)'
I want to use a string variable, and not a string directly.
How can I convert a QString variable to Utf8?
As seen here, QString::fromUtf8() does not accept an argument of type QString. You must give it a const char *, so you could rewrite it like this:
QMessageBox msg;
QString str = QString::fromUtf8("یا حسین");
msg.setText(str);
msg.exec();
its not good idea write like that
using this must be better
QString str(tr("ya hossein");
and use linguist and add persian translation file to your project http://qt-project.org/doc/qt-4.8/linguist-translators.html
and if you dont want use this, you must be sure your IDE or code editor (like qtcreator) use utf8 for saving files and just use
QString str("یا حسین");
it must be ok, i tested that so many times

How to save image using timestamp in qt [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am creating a GUI for windows PC. I want to store a series of images on the PC. The name of the images is identical. But I want to append them with timestamps. So, how to save image using timestamp in Qt?
in addition to that, the images shud be saved something like this example:
referenceImage<.date.><.time.>jpg
where date and time correspond to the date on and time at which the image was saved on the windows PC. I have tried the following too
Here i have implemented this at the click of a push button:-
void MainWindow::on_generateImagePushButton_clicked()
{
QDate date = QDate::currentDate();
QString dateString = date.toString();
QString path = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1].jpg").arg(dateString);
qDebug()<<"path: "<<path;
/*display current time*/
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString path2 = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1 %2].jpg").arg(dateString).arg(timeString);
qDebug()<<"path2: "<<path2;
/*converting from QString to char* */
QByteArray bA = path2.toLocal8Bit();
const char *c_charArray = bA.data();
/*saving image*/
IplImage *imgWithTimeStamp = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
cvSaveImage(c_charArray, imgWithTimeStamp);
}
The image gets saved with dateStamp, ie eg. goldenRefImg[Wed Feb 5 2014].jpg when I use string-path. But when I use string-path2, it does NOT save with dateStamp & timeStamp as i expect it to, i.e. goldenRefImg[Wed Feb 5 2014 10:47:32].jpg
But the qDebug statements showing path and path2 are displayed correctly.
Application Output:
Starting E:\QT1\timepass-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2010__Qt_SDK__Debug\debug\timepass.exe...
path: "E:\QT1\timeStampTrial\goldenRefImg[Wed Feb 5 2014].jpg"
path2: "E:\QT1\timeStampTrial\goldenRefImg[Wed Feb 5 2014 10:47:23].jpg"
Now i have just recollected that an image cannot be saved with special characters such as the colon : which's there in timeStamp. Can the time format be changed?
I tried this way:
path2.replace(":","-");
But the E:\ also gets converted into E-.Please guide. Thank u.
const QDateTime now = QDateTime::currentDateTime();
const QString timestamp = now.toString(QLatin1String("yyyyMMdd-hhmmsszzz"));
const QString filename = QString::fromLatin1("/some/path/someimage-%1.jpg").arg(timestamp);
This takes the current date/time, converts it to a string using QDateTime::toString() (the documentation lists the formatting options) and constructs the file name out of it.
Then just use filename with QImage::save() or QImageWriter.
/*display current date*/
QDate date = QDate::currentDate();
QString dateString = date.toString();
QString path = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1].jpg").arg(dateString);
qDebug()<<"path: "<<path;
/*display current time*/
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString path2 = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1 %2].jpg").arg(dateString).arg(timeString);
qDebug()<<"path2: "<<path2;
path2.replace(":","-");
path2.replace(1,1,":");
QByteArray bA = path2.toLocal8Bit();
const char *c_charArray = bA.data();
IplImage *imgWithTimeStamp = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
cvSaveImage(c_charArray, imgWithTimeStamp);
Thank you for all your suggestions #Dmitri Sazonov and #Frank Osterfeld

Qt Mkdir with a environment variable

QDir *temp = new QDir("%USERPROFILE%");
bool ok = temp->mkdir("abc");
and it does not work.
For portable Qt code, use static method QProcessEnvironment::systemEnvironment():
QProcessEnvironment env(QProcessEnvironment::systemEnvironment());
QDir *temp = new QDir(env.value("USERPROFILE")); // returns empty string for unset variable
bool ok = temp->mkdir("abc");
Alternative, as suggested in a comment of the actual question, you can also use
#include <cstdio>
QString envValue(QString::fromLocal8bit(::getenv("USERPROFILE"))); // standard, yet deprecated in Windows...
I'd prefer using the first alternative, letting Qt take care of character encoding stuff. If you want to use non-Qt functions, I think in Windows you should use getenv_s or _wgetenv_s to do this "properly".

Qt translation file (qm) info

I have some number of qm files for my app. (pr_en.qm, pr_ru.qm). I can load they by
translator.load(fileName, '.');
qApp->installTranslator(translator);
I want build dynamic menu (English, Russian) to select language. But, how can I extract such constants (English, Russian) from qm file instead of it's names (pr_en.qm, pr_ru.qm). Thanks.
I would suggest two ways of doing it:
First would be declaring special translator field like:
tr("__LANGNAME__") that would be in every translation file filled with proper language name (even native). Then you could list all available translations, load them one by one and use QTranslator::translate(const char * context, const char * sourceText, const char * disambiguation = 0) method.
Example:
QStringList availableLanguages;
QDirIterator qmIt(pathToQm, QStringList() << "*.qm", QDir::Files);
while(qmIt.hasNext())
{
qmIt.next();
QFileInfo finfo = qmIt.fileInfo();
QTranslator translator;
translator.load(finfo.baseName(), pathToQm);
availableLanguages << translator.translate("__LANGNAME__");
}
qDebug() << availableLanguages;
My second aproach would be with QLocale and QLocale::Language. I would create QLocale object for each base name of file in qm dir, and then use QLocale::Language enum to get language name with QLocale::languageToString method.

Qt json parser return parse error

I try to parse json string using this method:
QString ourJSONData = QString('{"couchdb":"Welcome","version":"1.0.1"}');
QString response = QString("[") + QString(ourJSONData) + QString("]");
QScriptEngine engine;
QScriptValue sc = engine.evaluate(response);
ui->label->setText(sc.toString());
But label return
SyntaxError: Parse error
I using Qt 4.7.4
What i do wrong? Thanks.
UPD:
Sorry, problem was in that string:
QString ourJSONData = QString('{"couchdb":"Welcome","version":"1.0.1"}');
need change to:
QString ourJSONData = QString("{\"couchdb\":\"Welcome\",\"version\":\"1.0.1\"}");
P.S. this method i found at http://blog.siegerstein.com/archives/134
I built your code in QtCreator in got a very helpful error message:
character constant too long for its type
It's because your ourJSONData variable is initialised with a text in single quotes, which is for single characters.
This will correct that initialisation. (I put a \ before each double-quote, and then changed the single-quotes to double):
QString ourJSONData = QString("{\"couchdb\":\"Welcome\",\"version\":\"1.0.1\"}");

Resources