I cannot use char '&' Qt Creator

Asked

Viewed 125 times

0

I am trying to return a Qstring, which will be used as a URL and I need to use '&' as a separator in the URL. However, when the character is placed in Qstring, it breaks the URL and what should appear after the '&' does not appear.

retorno = "start http://localhost:5000/robo/?Nome="+nome+"&Capital="+capital;

In this case, 'name' and 'capital' are Qstrings previously declared. I have tried declaring a Qchar with the ASCII code of&' and have the same error.

  • 1

    I can’t see a problem, it could be something where you’re using the variable. A [mcve] would be useful.

  • The return is sent to the system as follows system(return.toStdString(). c_str());

  • Isn’t it interaction problem with the console? I probably wouldn’t even do that

  • 1

    regardless of the &problem, it would probably be better in your case to use Qt’s own resources (or even OS natives) to start a process, rather than "start".

2 answers

2

This is because the & (And commercial - ampersand) is used by the system to separate two commands on the same line, is a "special" character, just like pipe (|) and the paranteses (( and )), and all can be escaped with ^

However if you are using Qt, it already has functions ready for this, which avoids you having to go through this trouble of escaping the characters, for example:

Using QProcess

Using Qprocess with Qstringlist you can pass the arguments and the "Qt" itself will escape them to you:

retorno = "http://localhost:5000/robo/?Nome="+nome+"&Capital="+capital;

QProcess process;
process.start("start", QStringList() << retorno);

What should probably already solve, however it is interesting to note that Qt itself has a class called QDesktopServices

Using QDesktopServices

Which already aims to interact with operating system functions, ie if you port your program to Linux or OSX will not need to change anything in this part (will depend on what else you did), example with openUrl (QUrl it is necessary):

retorno = "http://localhost:5000/robo/?Nome="+nome+"&Capital="+capital;

QDesktopServices::openUrl(QUrl(retorno));

Okay, so it will fetch the program from the system that is associated with the URL protocol, in the case HTTP will probably open the default browser and also will not need "escapes" (like the ^).

1

The problem was in the character '&' that was passed to the console. I put ' before each Qstring&' and the console understood as a character instead of a command.

  • The character & has a special meaning in Qt. It is used to indicate shortcut keys and control the focuses of the buttons,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.