//testqstring.cpp
#include <QApplication>
#include <QTextBrowser>
#include <QDebug>
#include <QTextStream>
void Test_setNum()
{
QString strTest;
//to Hex string
short numHex = 127;
strTest.setNum(numHex, 16);
qDebug()<<"Hex: "<<strTest;
//to Oct string
int numOct = 63;
strTest.setNum(numOct, 8);
qDebug()<<"Oct: "<<strTest;
//to normal Dec string
long numDec = 800;
strTest.setNum(numDec);
qDebug()<<"Normal: "<<strTest;
//to float string
float numFixed = 123.78999;
strTest.setNum(numFixed, 'f', 3);
qDebug()<<"Fixed: "<<strTest;
//to scientific double string
double numScientific = 456.78999;
strTest.setNum(numScientific, 'e', 6);
qDebug()<<"Scientific: "<<strTest;
}
void Test_arg()
{
//使用 strResult 存储 arg 返回的新对象
QString strResult;
//Dec
long numDec = 800;
QString strMod = QObject::tr("Normal: %1");
strResult = strMod.arg(numDec); //%1是占位符,第一个arg函数参数变量转后的字符串填充到 %1 位置
qDebug()<<"Mod: "<<strMod<<" \t Result: "<<strResult;
//Oct
int numOct = 63;
strResult = QObject::tr("Oct: %1").arg(numOct, 4, 8, QChar('0')); //numOct转换后为4字符域宽,8进制,填充0
qDebug()<<strResult;
//Hex
short numHex = 127;
QString strPrefix = QObject::tr("0x");
//占位符里可填充数值转的字符串,也可以直接填充原有的字符串
strResult = QObject::tr("Hex: %1%2").arg(strPrefix).arg(numHex, 0, 16); //串联:第一个arg函数参数填充到%1,第二个arg填充到%2
qDebug()<<strResult;
//double
QT-QString常用方法(数字转换字符串操作符、子串操作)
最新推荐文章于 2025-06-14 13:32:06 发布