QString用法总结

来源:互联网 发布:2009款mac mini拆机 编辑:程序博客网 时间:2024/06/07 10:02

构造QString

在 Qt 中如何构造一段格式化字符串?

当然,C 中的方法都是可行的,比如 stdio.h 里面的 snprintf 什么的。在 Qt 中QString 提供了更好用的函数。

  • arg

这个函数的具体声明不写了,它有20个重载,典型的示例代码如下:

   1: #include <QtCore/QCoreApplication>
   2: #include <iostream>
   3: #include <stdio.h>
   4: using namespace std;
   5: 
   6: int main()
   7: {
   8:     QString str = QString("Ggicci is %1 years old, and majors in %2.").arg(20).arg("Software Eng");
   9:     cout << str.toStdString() << endl;
  10:     return 0;
  11: }
输出结果:
Ggicci is 20 years old, and majors in Software Eng.
Press <RETURN> to close this window...

上面代码中的字符串 “Ggicci is %1 years old, and majors in %2.” 中的 %1 和 %2 为占位符,后面跟随的两个 arg() 函数中的参数分别对应两个占位符作为值插入。这种形式在 C# 中也有类似的体现(C#中输出一段文字):

Console.WriteLine("Ggicci is {0} years old, and majors in {1}.", 20, "Software Eng");

  • sprintf

  • QString & QString::sprintf ( const char * cformat, ... )

    这个函数和 C 中的也是差不多的用法,只不过它作为QString的一个成员函数,使用起来就相当方便了,如:

       1: #include <QtCore/QCoreApplication>
       2: #include <iostream>
       3: #include <stdio.h>
       4: using namespace std;
       5: int main()
       6: {
       7:     QString str2;
       8:     str2.sprintf("Ggicci is %d years old, and majors in %s.", 20, "Software Eng");
       9:     cout << str2.toStdString() << endl;
      10:     return 0;
      11: }

输入结果:

Ggicci is 20 years old, and majors in Software Eng.
Press <RETURN> to close this window...


qDebug()用法

首先在头文件中包含#include <QDebug>

在需要使用的地方插入:

         qDebug("intensity:%d",intensity[0][2]); (%d表示整数)

输出结果:

intensity:195

qDebug使用形式:

1、qDebug()<< 

如:

int nDebug;

QString strDebug;

qDebug()<< "This is for debug, nDebug="<<nDebug<<", strDebug="<<strDebug;

2、qDebug(字符串格式,格式替换实际值)

qDebug("This is for Debug, nDebug=%n, strDebug=%s", nDebug, QByteArray(strDebug.toLatin1).data());

用.sprintf()以及.arg()函数组成字符串输出亦可。 

字符串格式说明:
%a,%A 读入一个浮点值(仅C99有效)    
%c 读入一个字符    
%d 读入十进制整数    
%i 读入十进制,八进制,十六进制整数    
%o 读入八进制整数    
%x,%X 读入十六进制整数   
%s 读入一个字符串,遇空格、制表符或换行符结束。
注意:为了防止字符串中间有空格而停止,可以使用(“%s”,QByteArray(str.toLatin1()).data())格式,将字符串转换为字符数组形式。    
%f,%F,%e,%E,%g,%G 用来输入实数,可以用小数形式或指数形式输入。    
%p 读入一个指针    
%u 读入一个无符号十进制整数   
%n 至此已读入值的等价字符数    
%[] 扫描字符集合    

%% 读%符号


0 0
原创粉丝点击