QString New Line

我只是一个虾纸丫 提交于 2021-02-10 07:06:51

问题


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;

回答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.




回答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




回答3:


Also you can use endl as follow:

ErrorLog += "Company Name is empty" + endl;


来源:https://stackoverflow.com/questions/27620038/qstring-new-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!