QString New Line

32,457

Solution 1

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.

Solution 2

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

Solution 3

Also you can use endl as follow:

ErrorLog += "Company Name is empty" + endl;
Share:
32,457
Root0x
Author by

Root0x

Updated on July 19, 2022

Comments

  • Root0x
    Root0x almost 2 years

    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;