Qt QString的使用
1. QString的arg()函数
- 函数介绍:
QString::arg ( int a, int fieldWidth = 0, int base = 10, const QChar &fillChar = QLatin1Char(" ") ) const;
QString & QString::setNum(float n, char format = 'g', int precision = 6)
- 示例代码
QString str;
str = QString("Decimal 2 is %1 in hexadecimal").arg(0x02, 3, 16);//不带填充
str = QString("%1").arg(521,5,10,QChar('a')); //带填充
float bb = 1235.664252;
str= QString("%1").arg(bb, 0, 'f', 1);
上述函数执行效果:
Decimal 2 is 002 in hexadecimal aa521 1235.7
- 使用范例(结合QFile的使用):
只保留关键代码
///数据结构
struct channel{
int id;
QVector<float> value;
};
typedef struct channel Channel;
///模拟数据
QList<Channel *> channelList;
channelList.clear();
for(int i = 0; i < 12; i++)
{
Channel *c = new Channel;
c->id = i+1;
c->value.clear();
channelList.push_back(c);
if(i == 3)
{
continue;
}
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
for(int j = 0; j < 200; j++)
{
c->value.push_back((float)(qrand() % 10000));
}
}
///写文件
QFile raw_data("test.dat");
if(raw_data.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate))
{
QString line_data = "";
for(int i = 0; i < 12; i++)
{
QString name = "";
name.append(QString("CH%1").arg(i + 1, 2, 10, QChar('0')));
line_data.append(QString("%1").arg(name, 10, QChar(' ')));
}
line_data.append("\r");
raw_data.write(line_data.toStdString().data(), line_data.size());
for(int i = 0; i < 200; i++)
{
line_data.clear();
for(int j = 0; j < channelList.size(); j++)
{
if(channelList.at(j)->value.size() < (i + 1))
{
line_data.append(QString("%1").arg("NULL", 10));
}else{
line_data.append(QString("%1").arg(QString::number(channelList.at(j)->value.at(i)), 10, QChar(' ')));
}
}
line_data.append("\n");
raw_data.write(line_data.toStdString().data(), line_data.size());
}
raw_data.close();
}
上输代码运行的效果如下所示:
CH01 CH02 CH03 CH04 CH05 CH06 CH07 CH08 CH09 CH10 CH11 CH12
7699 7699 7699 NULL 7699 7699 7699 7699 7699 7699 7699 7699
3265 3265 3265 NULL 3265 3265 3265 3265 3265 3265 3265 3265
884 884 884 NULL 884 884 884 884 884 884 884 884
8231 8231 8231 NULL 8231 8231 8231 8231 8231 8231 8231 8231
9288 9288 9288 NULL 9288 9288 9288 9288 9288 9288 9288 9288
8683 8683 8683 NULL 8683 8683 8683 8683 8683 8683 8683 8683
8527 8527 8527 NULL 8527 8527 8527 8527 8527 8527 8527 8527
1964 1964 1964 NULL 1964 1964 1964 1964 1964 1964 1964 1964