QString的不常见用法

时间:2022-05-18 15:22:32

QString str("Hello");

QString str = "Hello";

static const QChar data[4] = { 0x0055, 0x006e, 0x10e3, 0x03a3 };
QString str(data, 4);

QString str;
str.resize(4);

str[0] = QChar('U');
str[1] = QChar('n');
str[2] = QChar(0x10e3);
str[3] = QChar(0x03a3);

QString str;
str.sprintf("%s %.3f", "float", 3.1415926);
//str结果是"float 3.14"

QString str;
str.setNum(10); //str = "10"
str.setNum(10, 16); //str = "a"
str.setNum(10.12345); //str = "10.12345"

QString i; // current file's number
QString total; // number of files to process
QString fileName; // current file's name

QString status = QString("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);

参考:http://blog.csdn.net/xgbing/article/details/7770854

------------------------------------------------------------------

1)Char * 初始化

QString str = "Hello";

QString converts the const char * data into Unicode using the fromAscii() function.

2)QChar[]数组初始化

  1. static const QChar data[4] = { 0x0055, 0x006e, 0x10e3, 0x03a3 };
  2. QString str(data, 4);

也可以这样

  1. QRegExp pattern;
  2. static const QChar unicode[] = { 0x005A, 0x007F, 0x00A4, 0x0060,
  3. 0x1009, 0x0020, 0x0020};
  4. int size = sizeof(unicode) / sizeof(QChar);
  5. QString str = QString::fromRawData(unicode, size);

3)还可以通过risize()函数和每个QChar字符进行初始化

  1. QString str;
  2. str.resize(4);
  3. str[0] = QChar('U');
  4. str[1] = QChar('n');
  5. str[2] = QChar(0x10e3);
  6. str[3] = QChar(0x03a3);

通过at()函数进行每个字符读取

  1. QString str;
  2. for (int i = 0; i < str.size(); ++i) {
  3. if (str.at(i) >= QChar('a') && str.at(i) <= QChar('f'))
  4. qDebug() << "Found character in range [a-f]";
  5. }

参考:http://qimo601.iteye.com/blog/1432867