【问题标题】:QString New LineQString 换行
【发布时间】:2014-12-23 12:06:02
【问题描述】:

我想在我的QString 中添加一个新行。我尝试使用\n,但收到“预期表达式”错误。我的代码示例如下:

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;

【问题讨论】:

  • 在 Qt 5.6 中,您需要在实际的引号内使用 \n\r\n

标签: c++ qt qstring qtcore


【解决方案1】:

在使用std::stringQString等时,需要使用operator+push_backappend或其他一些附加方式。逗号 (',') 不是连接字符。因此,这样写:

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";

还请注意,\n 在此上下文中足以确定文件、GUI 控件等的平台相关行结束(如果需要)。 Qt 会通过常规的标准手段、API,或者如果需要,它会自行解决。

公平地说,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");

实际上,当您使用常量字符串时,如果编译器支持相应的 C++11 功能,则值得考虑使用QStringLiteral,因为它会构建字符串编译时间。

【讨论】:

    【解决方案2】:

    我同意lpapp 的观点,您应该简单地将'\n' 合并到您要附加的字符串文字中。所以:

    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";
    }
    

    但我还想提一下,不仅 Qt,而且 C++ 通常会将 '\n' 转换为适合您平台的正确行尾。有关详细信息,请参阅此链接:http://en.wikipedia.org/wiki/Newline#In_programming_languages

    【讨论】:

      【解决方案3】:

      您也可以使用endl,如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-12
        • 1970-01-01
        • 1970-01-01
        • 2013-09-30
        相关资源
        最近更新 更多