Search code examples
c++qtqstringqtcore

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;

Solution

  • 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.