zoukankan      html  css  js  c++  java
  • QT 格式化字符串功能

    直接想到使用 sprintf(),写出如下的代码:

    1 void MainWindow::formatSerInfo(void)
    2 {
    3     QString strTest("Tst");
    4     QString strSerInfo;
    5     strSerInfo.sprintf("%s %d",strTest,m_baudRateCur);
    6     hintSerSts->setText(strSerInfo);
    7 }

    编译直接报错,错误信息如下:

    C:QtQtPrjSerialAssistmainwindow.cpp:427: error: cannot pass objects of non-trivially-copyable type 'class QString' through '...'
         strSerInfo.sprintf("%s %d",strTest,m_baudRateCur);
    C:QtQtPrjSerialAssistmainwindow.cpp:427: warning: format '%s' expects argument of type 'char*', but argument 3 has type 'QString' [-Wformat=]

    不支持 QString 的 sprintf, 使用起来最是不方便!

    QString 转 char * 还是比较麻烦的:

    先将 QString 转换为 QByteArray,再将 QByteArray 转换为 char *。

    注意:不能用下面的转换形式 char *mm = str.toLatin1().data(); 。因为这样的话,str.toLatin1() 得到的 QByteArray 类型结果就不能保存,最后转换,mm 的值就为空。

    示例:

    1 Qstring str;
    2 char *ch;
    3 QByteArray ba = str.toLatin1();    
    4 ch = ba.data();

    这样就完成了 QString 向 char * 的转化。经测试程序运行时不会出现 Bug。

    注意第三行,一定要加上,不可以 str.toLatin1().data() 这样一部完成,可能会出错。

    所以上述代码最后修改为:

    1 void MainWindow::formatSerInfo(void)
    2 {
    3     QString strTest("Tst");
    4     QString strSerInfo;
    5     QByteArray baTmp = strTest.toLatin1();
    6     strSerInfo.sprintf("%s %d",baTmp.data(),m_baudRateCur);
    7     hintSerSts->setText(strSerInfo);
    8 }

    或者,使用 arg 方法:

    1 void MainWindow::formatSerInfo(void)
    2 {
    3     QString strTest("Tst");
    4     QString strSerInfo;
    5     strSerInfo = QString("%1 %2").arg(strTest).arg(m_baudRateCur);
    6     hintSerSts->setText(strSerInfo);
    7 }

    在 QT 中,建议使用后面方法,即 arg() 的方法。

  • 相关阅读:
    记一次JVM Full GC (Metadata GC Threshold)调优经历
    非root用户启动nginx
    springboot项目报错解决:ERROR StatusLogger No Log4j 2 configuration file found
    分布式锁的常见实现思路
    虚拟机安装redis及宿主机连接测试
    使用console.log打印的内容不一定可信
    《数据库系统概论》第九章笔记
    《数据库系统概论》第六章笔记
    英文论文里的缩写:e.g. etc. et al. i.e.
    英文论文里的缩写:e.g. etc. et al. i.e.
  • 原文地址:https://www.cnblogs.com/91program/p/5288935.html
Copyright © 2011-2022 走看看