Qt编程基础 | 第五章-数据结构 | 5.1、QString

一、QString与常见类型之间的转换

1、QString 转 char *

QString foodName("food");
// QString --> QByteArray --> char *
char *food = foodName.toUtf8().data();
    
qDebug() << "foodName : " << food;

2、QString 转 wstring

// QString ==> wstring
QString str = "Hello world";
std::wstring wstr = str.toStdWString();

// wstring ==> QString
QString str1 = QString::fromStdWString(wstr);

3、QString 转 double

double转QString使用的是QString提供的静态方法number,如下:

// 参数1:要转换的double数
// 参数2:转换成的double的格式
// 参数3:小数保留的精度
QString QString::number(double n, char format = 'g', int precision = 6)

format参数指定转换后的小数格式,可以使用下面这些值

参数含义
eformat as [-]9.9e[+
Eformat as [-]9.9E[+
fformat as [-]9.9
guse e or f format, whichever is the most concise(简洁)
Guse E or f format, whichever is the most concise(简洁)
// QString ==> double
QString strNum = "12.3456";
double value = strNum.toDouble();

// double ==> QString
double value1 = 20.678;
QString str2 = QString::number(value1, 'f', 2);

4、QString 转 int

QString提供了一批重载的静态number方法,支持与int、long类型进行转换,如下:

// int 转 QString
QString QString::number(uint n, int base = 10)
QString QString::number(int n, int base = 10)
QString QString::number(ulong n, int base = 10)
QString QString::number(qlonglong n, int base = 10)

// QString 转 int
uint QString::toUInt(bool *ok = Q_NULLPTR, int base = 10) const
int QString::toInt(bool *ok = Q_NULLPTR, int base = 10) const

// 示例:
QString str = "FF";
bool ok;
int hex = str.toInt(&ok, 16);       // hex == 255, ok == true
int dec = str.toInt(&ok, 10);       // dec == 0, ok == false

二、QString格式化字符串

格式化字符串使用通过arg成员函数来实现的,arg有很多重载版本的成员函数,下面列出来一些常见的版本,如下:

重载一

QString arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
参数说明
const QString & a替换%1字符串
int fielldWidth = 0带默认参数,指定参数a占用最小空间
Qchar fillChar带默认参数,当 fielldWidth 为负数时,右对齐(在右边补);反则左对齐(左边补)

重载二

QString QString::arg(const QString & a1, const QString & a2) const
参数说明
const QString & a1替换%1的字符串
const QString & a2替换%2的字符串

示例:

QString currentIndex = QString("%1%2").arg(QStringLiteral("当前项索引:")).arg(index);

QString str1("str1");
QString str2("str2");
QString str3 = QString("%1%2").arg(str1, str2);

三、QString常见操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值