Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QString New Line

I want to add a new line to my QString. I tried to use \n, but I am receiving an error of "Expected Expression". An example of my code can be found below:

if (ui->lineEdit_Company_Name->text().isEmpty())
    ErrorLog = ErrorLog + "Company Name is empty", \r\n;
if(ui->lineEdit_Company_Owner->text().isEmpty())
    ErrorLog = ErrorLog + "Company Owner is empty", \r\n;
like image 672
Root0x Avatar asked Jun 14 '26 13:06

Root0x


2 Answers

You need to use operator+, push_back, append or some other means for appending when using std::string, QString and the like. Comma (',') is not a concatenation character. Therefore, write this:

if (ui->lineEdit_Company_Name->text().isEmpty())
    ErrorLog = ErrorLog + "Company Name is empty\n";
if(ui->lineEdit_Company_Owner->text().isEmpty())
    ErrorLog = ErrorLog + "Company Owner is empty\n";

Please also note that \n is enough in this context to figure out the platform dependent line end for files, GUI controls and the like if needed. Qt will go through the regular standard means, APIs or if needed, it will solve it on its own.

To be fair, you could simplify it even further:

if (ui->lineEdit_Company_Name->text().isEmpty())
    ErrorLog += "Company Name is empty\n";
    // or ErrorLog.append("Company Name is empty\n");
    // or ErrorLog.push_back("Company Name is empty\n");
if(ui->lineEdit_Company_Owner->text().isEmpty())
    ErrorLog += "Company Owner is empty\n";
    // or ErrorLog.append("Company Owner is empty\n");
    // or ErrorLog.push_back("Company Owner is empty\n");

Practically speaking, when you use constant string, it is worth considering the use of QStringLiteral as it builds the string compilation-time if the compiler supports the corresponding C++11 feature.

like image 179
lpapp Avatar answered Jun 16 '26 04:06

lpapp


I would concur with lpapp that you should simply incorporate the '\n' into the string literal you are appending. So:

if (ui->lineEdit_Company_Name->text().isEmpty()){
    ErrorLog += "Company Name is empty\n";
}
if(ui->lineEdit_Company_Owner->text().isEmpty()){
    ErrorLog += "Company Owner is empty\n";
}

But I'd like to also mention that the not just Qt, but C++ in general translates, '\n' to the correct line ending for your platform. See this link for more info: http://en.wikipedia.org/wiki/Newline#In_programming_languages

like image 37
Jonathan Mee Avatar answered Jun 16 '26 04:06

Jonathan Mee