QString& QString::operator=(const QByteArray&)' is private - c++

I am trying to read standard output from QProcess as QString where the passed argument is a linux command. The linux command gives me the linux username. When I pass the argument to QProcess I expect the output to be my linux username. In doing so I have to read the standard output and get the result as QString but I get the error:
QString& QString::operator=(const QByteArray&)' is private.
My code:
QProcess process;
process.start(QString::fromStdString("whoami"));
process.waitForFinished(-1); // will wait forever until finished
QByteArray name = process.readAllStandardOutput();
QString username = name; //Error here saying

QProcess process;
process.start(QString::fromStdString("whoami"));
process.waitForFinished(-1); // this could be omitted
QTextStream txtStream(&process);
QString username = txtStream.readLine();
Note QTextStream by default is using default locale string encoding what is preferred. You can use QTextStream::setCodec to change string encoding (UTF-8, Windows-1250, UCS or whatever you need, default codec from system locale is usually best choice).
It also allows you to process data in streamed manner and this is always good.

Simply do this:
QByteArray name = process.readAllStandardOutput();
QString username = QString::fromRawData(name.data(), name.size());

Related

Convert QByteArray to QString

I want to encrypt the data of a database and to do this, I used AES_128 in this link for encryption.
The result of encryption is a QByteArray and the QByteArray is saved on the text file in the correct shape and I could decode it correctly, but and I need to convert it to the QString and reverse to QByteArray to store and read it on the Sqlite DB. I tried some options like
QByteArray encodedText; QString DataAsString = QString(encodedText);
and
string DataAsString1 = encodedText.toStdString();
and
QString DataAsString = QTextCodec::codecForName("UTF-8") >toUnicode(encodedText);
and other solutions like this link, but the outputs of these options aren't in the correct way. Because after casting, I couldn't convert the encoded text to decoded correctly.
This is the input string of encoded text:
"\x14r\xF7""6#\xFE\xDB\xF0""D\x1B\xB5\x10\xEDx\xE1""F"
and these are the outputs for the different options:
\024r�6#���D\033�\020�x�F
and
\024r�6#���D\033�\020�x�F
Does anybody suggestion about the right conversion?
try to use this:
QString QString::fromUtf8(const QByteArray &str)

Using QProcess for CLI

How can I use QProcess for Command Line Interactive arguments, I am trying to a transfer a file usimg scp which prompts for password
QString program = "c:/temp/pscp.exe";
QStringList arguments;
arguments << "C:/Users/polaris8/Desktop/Test1GB.zip" << "Mrigendra#192.168.26.142:/home/";
QPointer<QProcess> myProcess;
myProcess = new QProcess;
connect(myProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput()));
myProcess->start(program , arguments);
After this the commnad Line asks for Password how to satisfy it using QProcess , can I overcome it by giving some options in my arguments only for scp, or what should be the code in my slot readOutput that throws the password to Command Line . Any suggestions would be helpful. Thanks
It seems that scp does not have such options, but pscp (sftp client does have). So, I would be writing something like this to extend your initial arguments with that option based on the following man page:
QString program = "c:/temp/pscp.exe";
QStringList arguments;
arguments << "-pw" << "password" << "C:/Users/polaris8/Desktop/Test1GB.zip" << "Mrigendra#192.168.26.142:/home/";
^^^^^^^^^^^^^^^^^^^
QPointer<QProcess> myProcess;
myProcess = new QProcess;
connect(myProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput()));
myProcess->start(program , arguments);
Also, I would encourage you to use QStandardPaths for a path like yours. See the documentation for details:
QStandardPaths::DesktopLocation 0 Returns the user's desktop directory.
So, you could eventually replace this string:
"C:/Users/polaris8/Desktop/Test1GB.zip"
with the following:
QStandardPaths::locate(QStandardPaths::DesktopLocation, "Test1GB.zip")
That being said, you may wish to consider using keys instead of password in the future. It would be a bit more secure, and also convenient for your application.
I think you can pass the username / password as options with:
-l user
-pw passwd
So your arguments should look like this:
QStringList arguments;
arguments << "-l" << "Mrigendra" << "-pw" << "Password" <<
"C:/Users/polaris8/Desktop/Test1GB.zip" <<
"192.168.26.142:/home/";

Load and display QString with proper encoding

I am trying to load a name from file that has several special characters and if it is in file (looks like meno: Marek Ružička/) display it. Code here:
QFile File("info/"+meno+".txt");
File.open(QIODevice::ReadOnly);
QVariant Data(File.readAll());
QString in = Data.toString(), pom;
if(in.contains("meno:")){
pom = in.split("meno:").at(1);
pom=pom.split("/").at(0);
ui->label_meno->setText(trUtf8("Celé meno: ")+pom);}
the part trUtf8("Celé meno: ") displays well but I cant find how to display string in pom, it alone looks like Marek RužiÄka, using toUtf8() function makes it Marek RuþiÃÂka, I've tried to convert it to stdString too but doesn't work either. I am not sure if the conversion from QFile to QVariant and to QString is right, if this causes problem how to read data properly?
Try this:
QTextCodec* utf = QTextCodec::codecForName("UTF-8");
QByteArray data = <<INPUT QBYTEARRAY>>.toUtf8();
QString utfString = utf->toUnicode(data);
qDebug() << utfString;
One of the right ways is to use QTextStream for the reading, and then you can specify the codec for utf 8 as follow:
in.setCodec("UTF-8");
See the documentation for further details:
void QTextStream::setCodec(const char * codecName)
Sets the codec for this stream to the QTextCodec for the encoding specified by codecName. Common values for codecName include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't recognized, nothing happens.
Example:
QTextStream out(&file);
out.setCodec("UTF-8");
Another right way would be to fix your current code without using QTextStream by using the dedicated QString method as follows:
QString in = QString::fromUtf8(File.readAll()), pom;
Please note that though you may wish to add more error handling into your code than available now.

Detect text file encoding

In my program I load plain text files supplied by the user:
QFile file(fileName);
file.open(QIODevice::ReadOnly);
QTextStream stream(&file);
const QString &text = stream.readAll();
This works fine when the files are UTF-8 encoded, but some users try to import Windows-1252 encoded files, and if they have words with special characters (for example "è" in "boutonnière"), those will show incorrectly.
Is there a way to detect the encoding, or at least distinguish between UTF-8 (possibly without BOM), and Windows-1252, without asking the user to tell me the encoding?
Turns out that auto-detecting the encoding is impossible for the general case.
However, there is a workaround to at least fall back to the system locale if the text is not valid UTF-8/UTF-16/UTF-32 text. It uses QTextCodec::codecForUtfText(), which tries to decode a byte array using UTF-8, UTF-16 and UTF-32, and returns the supplied default codec if it fails.
Code to do it:
QTextCodec *codec = QTextCodec::codecForUtfText(byteArray, QTextCodec::codecForName("System"));
const QString &text = codec->toUnicode(byteArray);
Update
The above code will not detect UTF-8 without BOM, however, as codecForUtfText() relies on the BOM markers. To detect UTF-8 without BOM, see https://stackoverflow.com/a/18228382/492336.
This trick works for me, at least so far. This method does not require BOM to work:
QTextCodec::ConverterState state;
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
const QByteArray data(readSource());
const QString text = codec->toUnicode(data.constData(), data.size(), &state);
if (state.invalidChars > 0)
{
// Not a UTF-8 text - using system default locale
QTextCodec * codec = QTextCodec::codecForLocale();
if (!codec)
return;
ui->textBrowser->setPlainText(codec->toUnicode(readSource()));
}
else
{
ui->textBrowser->setPlainText(text);
}

Specify default extension in QFileDialog::getSaveFileName

Is there an equivalent of the lpstrDefExt member of OPENFILENAME struct used in the Win32 function GetSaveFileName?
Here's description from MSDN:
LPCTSTR lpstrDefExt
The default extension. GetOpenFileName and GetSaveFileName append this
extension to the file name if the user fails to type an extension.
This string can be any length, but only the first three characters are
appended. The string should not contain a period (.). If this member
is NULL and the user fails to type an extension, no extension is
appended.
So if lpstrDefExt is set to "txt" and the user types "myfile" instead of "myfile.txt", the function still returns "myfile.txt".
Edit: If this does not work for you look at the answer below by #user52366
Qt will extract the default extension from the "selectedFilter" parameter, if specified.
Here is an example:
QString filter = "Worksheet Files (*.abd)";
QString filePath = QFileDialog::getSaveFileName(GetQtMainFrame(), tr("Save Worksheet"), defaultDir, filter, &filter);
When using this code the getSaveFileName() method will automatically add the ".abd" file extension if the user didn't specify one in the dialog. You can see the implementation of this in the qt_win_get_save_file_name() inside the "qfiledialog_win.cpp" Qt source file.
Unfortunately this doesn't work for the getOpenFileName() method.
As mentioned in the comment above, this does not work, at least for me.
In the end I skipped the static method and used the following:
QFileDialog dialog(this, "Save someting", QString(),
"Comma-separated file (*.csv)");
dialog.setDefaultSuffix(".csv");
dialog.setAcceptMode(QFileDialog::AcceptSave);
if (dialog.exec()) {
const auto fn = dialog.selectedFiles().front();
// a QStringList is returned but it always contains a single file
// do something using filename 'fn' ...
}
Not sure what exactly LPCTSTR lpstrDefExt is trying to do but Qt documentation gives the following example
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
"/home/jana/untitled.png",
tr("Images (*.png *.xpm *.jpg)"));
http://doc.qt.io/qt-5/qfiledialog.html#getSaveFileName