1.2 Qt常用基础类型

1. 基础类型

因为Qt是一个C++框架, 因此C++中所有的语法和数据类型在Qt中都是被支持的, 但是Qt中也定义了一些属于自己的数据类型, 下边给大家介绍一下这些基础的数据类型。

QT基本数据类型定义在`#include <QtGlobal>` 中,QT基本数据类型有:

类型名称 注释 备注
qint8 signed char 有符号 8 位数据
qint16 signed short 16 位数据类型
qint32 signed int 32 位有符号数据类型
qint64 long long int 或 (__int64) 64 位有符号数据类型,Windows 中定义为__int64
qintptr qint32 或 qint64 指针类型 根据系统类型不同而不同,32 位系统为 qint32、64 位系统为 qint64
qlonglong long long int 或 (unsigned __int64) Windows 中定义为__int64
qptrdiff qint32 或 qint64 根据系统类型不同而不同,32 位系统为 qint32、64 位系统为 qint64
qreal double 或 float 除非配置了 - qreal float 选项,否则默认为 double
quint8 unsigned char 无符号 8 位数据类型
quint16 unsigned short 无符号 16 位数据类型
quint32 unsigned int 无符号 32 位数据类型
quint64 unsigned long long int 或 (unsigned __int64) 无符号 64 比特数据类型,Windows 中定义为 unsigned __int64
quintptr qint32 或 qint64 根据系统类型不同而不同,32 位系统为 quint32、64 位系统为 quint64
qulonglong unsigned long long int 或 (unsigned __int64) Windows 中定义为__int64
uchar unsigned char 无符号字符类型
uint unsigned int 无符号整型
ulong unsigned long 无符号长整型
ushort unsigned short 无符号短整型

2. log输出

> 在Qt中进行log输出, 一般不使用c中的`printf`, 也不是使用C++中的`cout`, Qt框架提供了专门用于日志输出的类, 头文件名为 `QDebug`, 使用方法如下:

cpp 复制代码
// 包含了QDebug头文件, 直接通过全局函数 qDebug() 就可以进行日志输出了
qDebug() << "Date:" << QDate::currentDate();
qDebug() << "Types:" << QString("String") << QChar('x') << QRect(0, 10, 50, 40);
qDebug() << "Custom coordinate type:" << coordinate;

// 和全局函数 qDebug() 类似的日志函数还有: qWarning(), qInfo(), qCritical()
int number = 666;
float i = 11.11;
qWarning() << "Number:" << number << "Other value:" << i;
qInfo() << "Number:" << number << "Other value:" << i;
qCritical() << "Number:" << number << "Other value:" << i;

Detailed Description(详细说明)

当开发者需要向设备、文件、字符串或者控制台输出调试信息、跟踪日志时,可以使用 QDebug

Basic Use(基础用法)

在常规场景下,调用 qDebug() 函数来获取一个默认的 QDebug 对象,用于输出调试信息十分便捷。

cpp 复制代码
qDebug() << "Date:" << QDate::currentDate();
qDebug() << "Types:" << QString("String") << QChar('x') << QRect(0, 10, 50, 40);
qDebug() << "Custom coordinate type:" << coordinate;

<<操作符被重载过,可以一次性传入多种不同类型的数据。

该方式会调用接收QtMsgType类型(参数值为QtDebugMsg)的构造函数来创建 QDebug 对象。与之类似,qWarning()qCritical()qFatal() 函数同样会返回对应消息类型的 QDebug 对象。

QDebug 类还提供多种构造函数适配其他场景:

  • 支持传入QFile以及其他QIODevice子类,将调试信息写入文件或其他 IO 设备;
  • 支持传入QString,把日志写入字符串,用于后续展示或者序列化。

核心知识点解析 💡

  1. qDebug() 函数 vs QDebug
  • QDebug,负责日志输出功能;
  • qDebug()全局函数 ,调用后临时生成一个默认的 QDebug 对象,也就是我们日常最常写的 qDebug() << xxx;
  1. Qt 四类日志函数(对应不同消息等级)

表格

函数 消息类型 作用
qDebug() QtDebugMsg 普通调试信息(开发调试用)
qInfo() QtInfoMsg 普通运行信息(Qt5.5 新增)
qWarning() QtWarningMsg 警告信息,非致命异常
qCritical() QtCriticalMsg 严重错误
qFatal() QtFatalMsg 致命错误,输出后程序直接崩溃
  1. 支持自动打印 Qt 内置类型

就像示例代码所示:QDateQStringQCharQRect 等 Qt 容器 / 几何 / 时间类型,原生支持直接使用 << 传入 qDebug,无需手动转换字符串。

  1. 拓展功能(文档提到的高级用法)

QDebug 不只是打印到控制台:

  1. 重定向输出到文本文件:构造 QDebug 时传入 QFile 对象;
  2. 输出到QString:把日志先存到字符串,后续弹窗展示、网络发送;
cpp 复制代码
// 输出到字符串示例
QString logStr;
QDebug(&logStr) << "测试日志";
  1. 自定义类型打印(示例最后一行 coordinate

如果你自己写的结构体 / 类想要直接 qDebug() << 对象,需要重载 operator<<(QDebug debug, const YourClass &obj) 运算符。

举例:

cpp 复制代码
#include <QCoreApplication>  // ① 包含 Qt 核心应用类头文件(用于无界面控制台应用)
#include <QDebug>            // ② 包含 Qt 调试输出类头文件(提供 qDebug() 输出功能)

struct Coordinate           // ③ 定义一个简单的 C 风格结构体,包含 x 和 y 两个整数坐标
{
    int x;
    int y;
};

// ★ ④ 为自定义类型 Coordinate 重载 QDebug 输出运算符
//    作用:让 qDebug() 能够直接输出 Coordinate 对象
//    参数1:debug 是 QDebug 对象,用于构建输出流
//    参数2:c 是要输出的 Coordinate 对象的常量引用
QDebug operator<<(QDebug debug, const Coordinate &c)
{
    // ⑤ debug.nospace():禁用自动空格,让输出格式紧凑
    //    "Coord[" << c.x << "," << c.y << "]":拼接自定义格式的字符串
    debug.nospace() << "Coord[" << c.x << "," << c.y << "]";
    // ⑥ return debug.space():恢复默认的空格行为(不影响后续输出)
    return debug.space();
}

int main(int argc, char *argv[])
{
    // ⑦ 创建 Qt 核心应用对象(无 GUI 界面,适合控制台工具或服务器程序)
    QCoreApplication a(argc, argv);

    // ⑧ 使用 C++11 统一初始化语法创建 Coordinate 对象,x=100,y=200
    Coordinate coordinate{100, 200};

    // ⑨ ★ 使用 qDebug() 输出自定义信息
    //     因为重载了 operator<<,qDebug() 可以智能处理 Coordinate 类型
    //     输出格式:Custom coordinate type: Coord[100,200]
    qDebug() << "Custom coordinate type:" << coordinate;

    // ⑩ 进入 Qt 事件循环(对于控制台程序,exec() 会阻塞等待事件)
    return a.exec();
}

如果想在外面的exe文件也看到调试窗口,则需要在pro文件的config配置项中添加console属性再重新编译构建,就可以在控制台中显示要打印的数据。

这样就可以在控制台中显示日志内容

注意:如果没有控制台输出需要在左侧的项目中勾选在终端运行按钮

3. 字符串类型

cpp 复制代码
c => `char*`

c++ => `std::string`

Qt => `QByteArray`, `QString`

3.1 QByteArray

在Qt中`QByteArray`可以看做是c语言中 `char*`的升级版本。我们在使用这种类型的时候可通过这个类的构造函数申请一块动态内存,用于存储我们需要处理的字符串数据。

下面给大家介绍一下这个类中常用的一些API函数,`大家要养成遇到问题主动查询帮助文档的好习惯`。

3.1.1 构造函数

cpp 复制代码
// 构造空对象, 里边没有数据
QByteArray::QByteArray();
// 将data中的size个字符进行构造, 得到一个字节数组对象
// 如果 size==-1 函数内部自动计算字符串长度, 计算方式为: strlen(data)
QByteArray::QByteArray(const char *data, int size = -1);
// 构造一个长度为size个字节, 并且每个字节值都为ch的字节数组
QByteArray::QByteArray(int size, char ch);

QByteArray :: QByteArray ( )
    ↑           ↑        ↑
   类名     构造函数名   参数列表

这段代码展示的是 Qt 中 QByteArray 类的三种构造函数QByteArray 是 Qt 提供的字节数组容器 ,用于存储原始二进制数据或文本数据(以 char 为单位)。它的主要特点是比 std::string 更适合处理二进制数据和与 Qt 的网络、IO 类交互。

3.1.2 数据操作

cpp 复制代码
// 在尾部追加数据
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QByteArray &QByteArray::append(const QByteArray &ba);
void QByteArray::push_back(const QByteArray &other);

// 头部添加数据
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QByteArray &QByteArray::prepend(const QByteArray &ba);
void QByteArray::push_front(const QByteArray &other);

// 插入数据, 将ba插入到数组第 i 个字节的位置(从0开始)
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QByteArray &QByteArray::insert(int i, const QByteArray &ba);

// 删除数据
// 从大字符串中删除len个字符, 从第pos个字符的位置开始删除
QByteArray &QByteArray::remove(int pos, int len);
// 从字符数组的尾部删除 n 个字节
void QByteArray::chop(int n);
// 从字节数组的 pos 位置将数组截断 (前边部分留下, 后边部分被删除)
void QByteArray::truncate(int pos);
// 将对象中的数据清空, 使其为null
void QByteArray::clear();

// 字符串替换
// 将字节数组中的 子字符串 before 替换为 after
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after);

3.1.3 子字符串查找和判断

cpp 复制代码
// 判断字节数组中是否包含子字符串 ba, 包含返回true, 否则返回false
bool QByteArray::contains(const QByteArray &ba) const;
bool QByteArray::contains(const char *ba) const;
// 判断字节数组中是否包含子字符 ch, 包含返回true, 否则返回false
bool QByteArray::contains(char ch) const;

// 判断字节数组是否以字符串 ba 开始, 是返回true, 不是返回false
bool QByteArray::startsWith(const QByteArray &ba) const;
bool QByteArray::startsWith(const char *ba) const;
// 判断字节数组是否以字符 ch 开始, 是返回true, 不是返回false
bool QByteArray::startsWith(char ch) const;

// 判断字节数组是否以字符串 ba 结尾, 是返回true, 不是返回false
bool QByteArray::endsWith(const QByteArray &ba) const;
bool QByteArray::endsWith(const char *ba) const;
// 判断字节数组是否以字符 ch 结尾, 是返回true, 不是返回false
bool QByteArray::endsWith(char ch) const;

3.1.4 遍历

cpp 复制代码
// 使用迭代器
iterator QByteArray::begin();
iterator QByteArray::end();

// 使用数组的方式进行遍历
// i的取值范围 0 <= i < size()
char QByteArray::at(int i) const;
char QByteArray::operator[](int i) const;

3.1.5 查看字节数

cpp 复制代码
// 返回字节数组对象中字符的个数
int QByteArray::length() const;
int QByteArray::size() const;
int QByteArray::count() const;

// 返回字节数组对象中 子字符串ba 出现的次数
int QByteArray::count(const QByteArray &ba) const;
int QByteArray::count(const char *ba) const;
// 返回字节数组对象中 字符串ch 出现的次数
int QByteArray::count(char ch) const;

3.1.6 类型转换

cpp 复制代码
// 将QByteArray类型的字符串 转换为 char* 类型
char *QByteArray::data();
const char *QByteArray::data() const;

// int, short, long, float, double -> QByteArray
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QByteArray &QByteArray::setNum(int n, int base = 10);
QByteArray &QByteArray::setNum(short n, int base = 10);
QByteArray &QByteArray::setNum(qlonglong n, int base = 10);
QByteArray &QByteArray::setNum(float n, char f = 'g', int prec = 6);
QByteArray &QByteArray::setNum(double n, char f = 'g', int prec = 6);
[static] QByteArray QByteArray::number(int n, int base = 10);
[static] QByteArray QByteArray::number(qlonglong n, int base = 10);
[static] QByteArray QByteArray::number(double n, char f = 'g', int prec = 6);

// QByteArray -> int, short, long, float, double
int QByteArray::toInt(bool *ok = Q_NULLPTR, int base = 10) const;
short QByteArray::toShort(bool *ok = Q_NULLPTR, int base = 10) const;
long QByteArray::toLong(bool *ok = Q_NULLPTR, int base = 10) const;
float QByteArray::toFloat(bool *ok = Q_NULLPTR) const;
double QByteArray::toDouble(bool *ok = Q_NULLPTR) const;

// std::string -> QByteArray
[static] QByteArray QByteArray::fromStdString(const std::string &str);
// QByteArray -> std::string
std::string QByteArray::toStdString() const;

// 所有字符转换为大写
QByteArray QByteArray::toUpper() const;
// 所有字符转换为小写
QByteArray QByteArray::toLower() const;

3.2 QString

> QString也是封装了字符串, 但是内部的编码为`utf8`, UTF-8属于Unicode字符集, 它固定使用多个字节(window为2字节, linux为3字节)来表示一个字符,这样可以将世界上几乎所有语言的常用字符收录其中。

> 下面给大家介绍一下这个类中常用的一些API函数。

3.2.1 构造函数

cpp 复制代码
// 构造一个空字符串对象
QString::QString();
// 将 char* 字符串 转换为 QString 类型
QString::QString(const char *str);
// 将 QByteArray 转换为 QString 类型
QString::QString(const QByteArray &ba);
// 其他重载的同名构造函数可参考Qt帮助文档, 此处略

3.2.2 数据操作

cpp 复制代码
// 尾部追加数据
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QString &QString::append(const QString &str);
QString &QString::append(const char *str);
QString &QString::append(const QByteArray &ba);
void QString::push_back(const QString &other);

// 头部添加数据
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QString &QString::prepend(const QString &str);
QString &QString::prepend(const char *str);
QString &QString::prepend(const QByteArray &ba);
void QString::push_front(const QString &other);

// 插入数据, 将 str 插入到字符串第 position 个字符的位置(从0开始)
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QString &QString::insert(int position, const QString &str);
QString &QString::insert(int position, const char *str);
QString &QString::insert(int position, const QByteArray &str);

// 删除数据
// 从大字符串中删除len个字符, 从第pos个字符的位置开始删除
QString &QString::remove(int position, int n);

// 从字符串的尾部删除 n 个字符
void QString::chop(int n);
// 从字节串的 position 位置将字符串截断 (前边部分留下, 后边部分被删除)
void QString::truncate(int position);
// 将对象中的数据清空, 使其为null
void QString::clear();

// 字符串替换
// 将字节数组中的 子字符串 before 替换为 after
// 参数 cs 为是否区分大小写, 默认区分大小写
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive);

3.2.3 子字符串查找和判断

cpp 复制代码
// 参数 cs 为是否区分大小写, 默认区分大小写
// 其他重载的同名函数可参考Qt帮助文档, 此处略

// 判断字符串中是否包含子字符串 str, 包含返回true, 否则返回false
bool QString::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

// 判断字符串是否以字符串 ba 开始, 是返回true, 不是返回false
bool QString::startsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

// 判断字符串是否以字符串 ba 结尾, 是返回true, 不是返回false
bool QString::endsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

3.2.4 遍历

cpp 复制代码
// 使用迭代器
iterator QString::begin();
iterator QString::end();

// 使用数组的方式进行遍历
// i的取值范围 0 <= position < size()
const QChar QString::at(int position) const
const QChar QString::operator[](int position) const;

3.2.5 查看字节数

cpp 复制代码
// 返回字节数组对象中字符的个数
int QString::length() const;
int QString::size() const;
int QString::count() const;

// 返回字节串对象中 子字符串 str 出现的次数
// 参数 cs 为是否区分大小写, 默认区分大小写
int QString::count(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

3.2.6 类型转换

cpp 复制代码
// int, short, long, float, double -> QString
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QString &QString::setNum(int n, int base = 10);
QString &QString::setNum(short n, int base = 10);
QString &QString::setNum(long n, int base = 10);
QString &QString::setNum(float n, char format = 'g', int precision = 6);
QString &QString::setNum(double n, char format = 'g', int precision = 6);
[static] QString QString::number(long n, int base = 10);
[static] QString QString::number(int n, int base = 10);
[static] QString QString::number(double n, char format = 'g', int precision = 6);

// QString -> int, short, long, float, double
int QString::toInt(bool *ok = Q_NULLPTR, int base = 10) const;
short QString::toShort(bool *ok = Q_NULLPTR, int base = 10) const;
long QString::toLong(bool *ok = Q_NULLPTR, int base = 10) const
float QString::toFloat(bool *ok = Q_NULLPTR) const;
double QString::toDouble(bool *ok = Q_NULLPTR) const;

// std::string -> QString
[static] QString QString::fromStdString(const std::string &str);
// QString -> std::string
std::string QString::toStdString() const;

// QString -> QByteArray
// 转换为本地编码, 跟随操作系统
QByteArray QString::toLocal8Bit() const;
// 转换为 Latin-1 编码的字符串 不支持中文
QByteArray QString::toLatin1() const;
// 转换为 utf8 编码格式的字符串 (常用)
QByteArray QString::toUtf8() const;

// 所有字符转换为大写
QString QString::toUpper() const;
// 所有字符转换为小写
QString QString::toLower() const;
一、数值 → QString 转换

setNum() 成员方法(修改自身)

cpp 复制代码
// 将 int 类型数字 n 转换为字符串,base 为进制(默认10进制)
// 修改当前 QString 对象,返回自身引用以支持链式调用
QString &QString::setNum(int n, int base = 10);

// 将 short 类型数字 n 转换为字符串,base 为进制
QString &QString::setNum(short n, int base = 10);

// 将 long 类型数字 n 转换为字符串,base 为进制
QString &QString::setNum(long n, int base = 10);

// 将 float 类型数字 n 转换为字符串
// format: 'f'=固定小数, 'e'=科学计数法, 'g'=自动选择(默认)
// precision: 小数精度位数
QString &QString::setNum(float n, char format = 'g', int precision = 6);

// 将 double 类型数字 n 转换为字符串
// 参数同上,支持更高精度的浮点数
QString &QString::setNum(double n, char format = 'g', int precision = 6);
cpp 复制代码
// 使用示例
QString str;
str.setNum(123);          // str = "123"
str.setNum(255, 16);      // str = "ff"(十六进制)
str.setNum(3.14159, 'f', 2); // str = "3.14"(保留2位小数)
str.setNum(3.14159, 'e', 2); // str = "3.14e+00"(科学计数法)

number() 静态方法(返回新对象)

cpp 复制代码
// 将 long 类型数字 n 转换为字符串,返回新的 QString 对象(不修改任何已有对象)
[static] QString QString::number(long n, int base = 10);

// 将 int 类型数字 n 转换为字符串,返回新的 QString 对象
[static] QString QString::number(int n, int base = 10);

// 将 double 类型数字 n 转换为字符串
// format: 'f'=固定小数, 'e'=科学计数法, 'g'=自动选择(默认)
// precision: 小数精度位数
[static] QString QString::number(double n, char format = 'g', int precision = 6);
cpp 复制代码
// 使用示例
QString s1 = QString::number(456);       // "456"
QString s2 = QString::number(255, 16);   // "ff"
QString s3 = QString::number(3.14);      // "3.14"
QString s4 = QString::number(3.14159, 'f', 3); // "3.142"
二、QString → 数值转换
cpp 复制代码
// 将字符串转换为 int 类型整数
// ok: 输出参数,转换成功设为 true,失败设为 false
// base: 进制(默认10),支持2~36
int QString::toInt(bool *ok = Q_NULLPTR, int base = 10) const;

// 将字符串转换为 short 类型整数
short QString::toShort(bool *ok = Q_NULLPTR, int base = 10) const;

// 将字符串转换为 long 类型整数
long QString::toLong(bool *ok = Q_NULLPTR, int base = 10) const;

// 将字符串转换为 float 类型浮点数
float QString::toFloat(bool *ok = Q_NULLPTR) const;

// 将字符串转换为 double 类型浮点数(精度更高)
double QString::toDouble(bool *ok = Q_NULLPTR) const;
cpp 复制代码
// 使用示例
QString str = "123";
bool ok;
int val = str.toInt(&ok);     // val = 123, ok = true

QString hex = "ff";
int hexVal = hex.toInt(&ok, 16); // hexVal = 255

QString invalid = "abc";
int bad = invalid.toInt(&ok); // bad = 0, ok = false

QString pi = "3.14";
double d = pi.toDouble(&ok);  // d = 3.14, ok = true
三、与 std::string 互转
cpp 复制代码
// 将 std::string 转换为 QString(UTF-8 编码)
[static] QString QString::fromStdString(const std::string &str);

// 将 QString 转换为 std::string(UTF-8 编码)
std::string QString::toStdString() const;
cpp 复制代码
// 使用示例
#include <string>

std::string cppStr = "Hello C++";
QString qstr = QString::fromStdString(cppStr);

QString qstr2 = "Hello Qt";
std::string cppStr2 = qstr2.toStdString();
四、与 QByteArray 互转
cpp 复制代码
// 将 QString 转换为操作系统本地编码的 QByteArray
// Windows下通常是 GBK/GB2312,Linux下是 UTF-8
QByteArray QString::toLocal8Bit() const;

// 将 QString 转换为 Latin-1(ISO-8859-1)编码
// ⚠️ 不支持中文!中文会变成乱码 '?'
QByteArray QString::toLatin1() const;

// 将 QString 转换为 UTF-8 编码的 QByteArray
// ✅ 最常用!支持所有 Unicode 字符
QByteArray QString::toUtf8() const;
cpp 复制代码
// 使用示例
QString str = "你好世界";

// ✅ 推荐:网络传输、文件存储
QByteArray utf8Data = str.toUtf8();    // UTF-8 编码

// ⚠️ 系统编码(Windows下是GBK,Linux下是UTF-8)
QByteArray localData = str.toLocal8Bit();

// ❌ 不推荐:中文会丢失
QByteArray latinData = str.toLatin1(); // 输出 "????"

// 反向转换
QString fromUtf8 = QString::fromUtf8(utf8Data);
QString fromLocal = QString::fromLocal8Bit(localData);

QString不能直接转换成char*,必须先转换成QByteArray再转换成char*

五、大小写转换
cpp 复制代码
// 将所有字符转换为大写,返回新的 QString 对象(不修改原对象)
QString QString::toUpper() const;

// 将所有字符转换为小写,返回新的 QString 对象(不修改原对象)
QString QString::toLower() const;

// 使用示例
QString str = "Hello World";
QString upper = str.toUpper();    // "HELLO WORLD"
QString lower = str.toLower();    // "hello world"
// str 本身仍是 "Hello World"

总结:

setNum()/number() 将数值转为字符串,toInt()/toDouble() 反向转换;toUtf8()/fromUtf8() 与 QByteArray 互转(最常用),toUpper()/toLower() 处理大小写。

3.2.7 字符串格式

cpp 复制代码
// 其他重载的同名函数可参考Qt帮助文档, 此处略
QString QString::arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char( ' ' )) const;
QString QString::arg(int a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char( ' ' )) const;

// 示例程序
int i;           // current file's number
int 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);
总结

arg() 是 Qt 中用于字符串格式化(类似 printf 但更安全)的方法,用参数替换字符串中的 %1%2%3... 占位符。

cpp 复制代码
// ① 用 QString 替换占位符
QString QString::arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const;

// ② 用 int 替换占位符(可指定进制)
QString QString::arg(int a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const;
参数 说明 默认值
a 要替换的值 ---
fieldWidth 最小字段宽度(不足时用 fillChar 填充) 0(不填充)
base 进制(2~36),仅数值类型有效 10
fillChar 填充字符 空格 ' '

核心工作原理

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

执行过程

  1. 第一个 .arg(i)%1 替换为 i 的值

  2. 第二个 .arg(total)%2 替换为 total 的值

  3. 第三个 .arg(fileName)%3 替换为 fileName 的值

注意 :替换是按顺序 进行的,%1 对应第一次调用 arg()%2 对应第二次调用,依此类推。

cpp 复制代码
#include <QString>
#include <QDebug>

int main() {
    int i = 5;
    int total = 10;
    QString fileName = "data.txt";

    // ★ 基础用法:占位符从 %1 开始
    QString status = QString("Processing file %1 of %2: %3")
                        .arg(i)
                        .arg(total)
                        .arg(fileName);
    qDebug() << status;   // "Processing file 5 of 10: data.txt"

    // ★ 链式调用可以换行,清晰易读
    QString msg = QString("User %1 logged in at %2")
                    .arg("admin")
                    .arg("10:30 AM");
    qDebug() << msg;   // "User admin logged in at 10:30 AM"

    // ★ 数值进制转换
    QString hex = QString("Hex: %1, Dec: %2")
                    .arg(255, 0, 16)   // 16进制
                    .arg(255);          // 10进制
    qDebug() << hex;   // "Hex: ff, Dec: 255"

    // ★ 字段宽度和填充
    QString padded = QString("ID: %1")
                        .arg(42, 6, 10, '0');   // 宽度6,用0填充
    qDebug() << padded;   // "ID: 000042"
}

注意事项

要点 说明
占位符从 %1 开始 不是 %0!这一点与 Python 等语言不同
arg() 调用顺序替换 第一个 arg() 替换 %1,第二个替换 %2,依此类推
类型安全 不同类型有对应的 arg() 重载,编译器会检查
性能 链式调用会创建临时对象,但 Qt 有优化,一般无需担心

4. QVariant

> QVariant这个类很神奇,或者说方便。很多时候,需要几种不同的数据类型需要传递,如果用结构体,又不大方便,容器保存的也只是一种数据类型,而QVariant则可以统统搞定。

> QVariant 这个类型充当着最常见的数据类型的联合。QVariant 可以保存很多Qt的数据类型,包括`QBrush、QColor、QCursor、QDateTime、QFont、QKeySequence、 QPalette、QPen、QPixmap、QPoint、QRect、QRegion、QSize和QString`,并且还有C++基本类型,如` int、float`等。

4.1 标准类型

* 将标准类型转换为QVariant类型

cpp 复制代码
// 这类转换需要使用QVariant类的构造函数, 由于比较多, 大家可自行查阅Qt帮助文档, 在这里简单写几个
QVariant::QVariant(int val);
QVariant::QVariant(bool val);
QVariant::QVariant(double val);
QVariant::QVariant(const char *val);
QVariant::QVariant(const QByteArray &val);
QVariant::QVariant(const QString &val);
......

// 使用设置函数也可以将支持的类型的数据设置到QVariant对象中
// 这里的 T 类型, 就是QVariant支持的类型
void QVariant::setValue(const T &value);
// 该函数行为和 setValue() 函数完全相同
[static] QVariant QVariant::fromValue(const T &value);
// 例子:
#if 1
QVariant v;
v.setValue(5);
#else
QVariant v = QVariant::fromValue(5);
#endif

int i = v.toInt();          // i is now 5
QString s = v.toString();   // s is now "5"

判断 QVariant中封装的实际数据类型

cpp 复制代码
// 该函数的返回值是一个枚举类型, 可通过这个枚举判断出实际是什么类型的数据
Type QVariant::type() const;

返回值`Type`的部分枚举定义, 全部信息可以自行查阅Qt帮助文档

将QVariant对象转换为实际的数据类型

cpp 复制代码
// 如果要实现该操作, 可以使用QVariant类提供的 toxxx() 方法, 全部转换可以参考Qt帮助文档
// 在此举列举几个常用函数:
bool QVariant::toBool() const;
QByteArray QVariant::toByteArray() const;
double QVariant::toDouble(bool *ok = Q_NULLPTR) const;
float QVariant::toFloat(bool *ok = Q_NULLPTR) const;
int QVariant::toInt(bool *ok = Q_NULLPTR) const;
QString QVariant::toString() const;
......

4.2 自定义类型

> 除了标准类型, 我们自定义的类型也可以使用`QVariant`类进行封装, `被QVariant存储的数据类型需要有一个默认的构造函数和一个拷贝构造函数`。为了实现这个功能,首先必须使用`Q_DECLARE_METATYPE()`宏。通常会将这个宏放在类的声明所在头文件的下面, 原型为:

> `Q_DECLARE_METATYPE(Type)`

> 使用的具体步骤如下:

* 第一步: 在头文件中声明

cpp 复制代码
// *.h
struct MyTest
{
    int id;
    QString name;
};
// 自定义类型注册
Q_DECLARE_METATYPE(MyTest)

第二步: 在源文件中定义

cpp 复制代码
MyTest t;
t.name = "张三丰";
t.num = 666;
// 值的封装
QVariant vt = QVariant::fromValue(t);

// 值的读取
if(vt.canConvert<MyTest>())
{
    MyTest t = vt.value<MyTest>();
    qDebug() << "name: " << t.name << ", num: " << t.num;
}

操作涉及的API如下:

cpp 复制代码
// Returns true if the variant can be converted to the template type T, otherwise false.
// 如果当前QVariant对象可用转换为对应的模板类型 T, 返回true, 否则返回false
bool QVariant::canConvert() const;
// 将当前QVariant对象转换为实际的 T 类型
T QVariant::value() const;

5. 位置和尺寸

> 在QT中我们常见的 点, 线, 尺寸, 矩形 都被进行了封装, 下边依次为大家介绍相关的类。

5.1 QPoint

> `QPoint`类封装了我们常用用到的坐标点 (x, y), 常用的 API如下:

cpp 复制代码
// 构造函数
// 构造一个坐标原点, 即(0, 0)
QPoint::QPoint();
// 参数为 x轴坐标, y轴坐标
QPoint::QPoint(int xpos, int ypos);

// 设置x轴坐标
void QPoint::setX(int x);
// 设置y轴坐标
void QPoint::setY(int y);

// 得到x轴坐标
int QPoint::x() const;
// 得到x轴坐标的引用
int &QPoint::rx();
// 得到y轴坐标
int QPoint::y() const;
// 得到y轴坐标的引用
int &QPoint::ry();

// 直接通过坐标对象进行算术运算: 加减乘除
QPoint &QPoint::operator*=(float factor);
QPoint &QPoint::operator*=(double factor);
QPoint &QPoint::operator*=(int factor);
QPoint &QPoint::operator+=(const QPoint &point);
QPoint &QPoint::operator-=(const QPoint &point);
QPoint &QPoint::operator/=(qreal divisor);

// 其他API请自行查询Qt帮助文档, 不要犯懒哦哦哦哦哦......

5.2 QLine

QLine`是一个直线类, 封装了两个坐标点 (`两点确定一条直线`)

常用API如下:

cpp 复制代码
// 构造函数
// 构造一个空对象
QLine::QLine();
// 构造一条直线, 通过两个坐标点
QLine::QLine(const QPoint &p1, const QPoint &p2);
// 从点 (x1, y1) 到 (x2, y2)
QLine::QLine(int x1, int y1, int x2, int y2);

// 给直线对象设置坐标点
void QLine::setPoints(const QPoint &p1, const QPoint &p2);
// 起始点(x1, y1), 终点(x2, y2)
void QLine::setLine(int x1, int y1, int x2, int y2);
// 设置直线的起点坐标
void QLine::setP1(const QPoint &p1);
// 设置直线的终点坐标
void QLine::setP2(const QPoint &p2);

// 返回直线的起始点坐标
QPoint QLine::p1() const;
// 返回直线的终点坐标
QPoint QLine::p2() const;
// 返回值直线的中心点坐标, (p1() + p2()) / 2
QPoint QLine::center() const;

// 返回值直线起点的 x 坐标
int QLine::x1() const;
// 返回值直线终点的 x 坐标
int QLine::x2() const;
// 返回值直线起点的 y 坐标
int QLine::y1() const;
// 返回值直线终点的 y 坐标
int QLine::y2() const;

// 用给定的坐标点平移这条直线
void QLine::translate(const QPoint &offset);
void QLine::translate(int dx, int dy);
// 用给定的坐标点平移这条直线, 返回平移之后的坐标点
QLine QLine::translated(const QPoint &offset) const;
QLine QLine::translated(int dx, int dy) const;

// 直线对象进行比较
bool QLine::operator!=(const QLine &line) const;
bool QLine::operator==(const QLine &line) const;

// 其他API请自行查询Qt帮助文档, 不要犯懒哦哦哦哦哦......

5.3 QSize

> 在QT中`QSize`类用来形容长度和宽度, 常用的API如下:

cpp 复制代码
// 构造函数
// 构造空对象, 对象中的宽和高都是无效的
QSize::QSize();
// 使用宽和高构造一个有效对象
QSize::QSize(int width, int height);

// 设置宽度
void QSize::setWidth(int width)
// 设置高度
void QSize::setHeight(int height);

// 得到宽度
int QSize::width() const;
// 得到宽度的引用
int &QSize::rwidth();
// 得到高度
int QSize::height() const;
// 得到高度的引用
int &QSize::rheight();

// 交换高度和宽度的值
void QSize::transpose();
// 交换高度和宽度的值, 返回交换之后的尺寸信息
QSize QSize::transposed() const;

// 进行算法运算: 加减乘除
QSize &QSize::operator*=(qreal factor);
QSize &QSize::operator+=(const QSize &size);
QSize &QSize::operator-=(const QSize &size);
QSize &QSize::operator/=(qreal divisor);

// 其他API请自行查询Qt帮助文档, 不要犯懒哦哦哦哦哦......

5.4 QRect

> 在Qt中使用 `QRect`类来描述一个矩形, 常用的API如下:

cpp 复制代码
// 构造函数
// 构造一个空对象
QRect::QRect();
// 基于左上角坐标, 和右下角坐标构造一个矩形对象
QRect::QRect(const QPoint &topLeft, const QPoint &bottomRight);
// 基于左上角坐标, 和 宽度, 高度构造一个矩形对象
QRect::QRect(const QPoint &topLeft, const QSize &size);
// 通过 左上角坐标(x, y), 和 矩形尺寸(width, height) 构造一个矩形对象
QRect::QRect(int x, int y, int width, int height);

// 设置矩形的尺寸信息, 左上角坐标不变
void QRect::setSize(const QSize &size);
// 设置矩形左上角坐标为(x,y), 大小为(width, height)
void QRect::setRect(int x, int y, int width, int height);
// 设置矩形宽度
void QRect::setWidth(int width);
// 设置矩形高度
void QRect::setHeight(int height);

// 返回值矩形左上角坐标
QPoint QRect::topLeft() const;
// 返回矩形右上角坐标
// 该坐标点值为: QPoint(left() + width() -1, top())
QPoint QRect::topRight() const;
// 返回矩形左下角坐标
// 该坐标点值为: QPoint(left(), top() + height() - 1)
QPoint QRect::bottomLeft() const;
// 返回矩形右下角坐标
// 该坐标点值为: QPoint(left() + width() -1, top() + height() - 1)
QPoint QRect::bottomRight() const;
// 返回矩形中心点坐标
QPoint QRect::center() const;

// 返回矩形上边缘y轴坐标
int QRect::top() const;
int QRect::y() const;
// 返回值矩形下边缘y轴坐标
int QRect::bottom() const;
// 返回矩形左边缘 x轴坐标
int QRect::x() const;
int QRect::left() const;
// 返回矩形右边缘x轴坐标
int QRect::right() const;

// 返回矩形的高度
int QRect::width() const;
// 返回矩形的宽度
int QRect::height() const;
// 返回矩形的尺寸信息
QSize QRect::size() const;

6. 日期和时间

6.1. QDate

cpp 复制代码
// 构造函数
QDate::QDate();
QDate::QDate(int y, int m, int d);

// 公共成员函数
// 重新设置日期对象中的日期
bool QDate::setDate(int year, int month, int day);
// 给日期对象添加 ndays 天
QDate QDate::addDays(qint64 ndays) const;
// 给日期对象添加 nmonths 月
QDate QDate::addMonths(int nmonths) const;
// 给日期对象添加 nyears 月
QDate QDate::addYears(int nyears) const;

// 得到日期对象中的年/月/日
int QDate::year() const;
int QDate::month() const;
int QDate::day() const;
void QDate::getDate(int *year, int *month, int *day) const;

// 日期对象格式化
/*
    d         -     The day as a number without a leading zero (1 to 31)
    dd        -    The day as a number with a leading zero (01 to 31)
    ddd        -    The abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses the system 
                locale to localize the name, i.e. QLocale::system().
    dddd    -     The long localized day name (e.g. 'Monday' to 'Sunday'). 
                Uses the system locale to localize the name, i.e. QLocale::system().
    M        -    The month as a number without a leading zero (1 to 12)
    MM        -    The month as a number with a leading zero (01 to 12)
    MMM        -    The abbreviated localized month name (e.g. 'Jan' to 'Dec'). 
                Uses the system locale to localize the name, i.e. QLocale::system().
    MMMM    -    The long localized month name (e.g. 'January' to 'December'). 
                Uses the system locale to localize the name, i.e. QLocale::system().
    yy        -    The year as a two digit number (00 to 99)
    yyyy    -    The year as a four digit number. If the year is negative, 
                a minus sign is prepended, making five characters.
*/
QString QDate::toString(const QString &format) const;

// 操作符重载 ==> 日期比较
bool QDate::operator!=(const QDate &d) const;
bool QDate::operator<(const QDate &d) const;
bool QDate::operator<=(const QDate &d) const;
bool QDate::operator==(const QDate &d) const;
bool QDate::operator>(const QDate &d) const;
bool QDate::operator>=(const QDate &d) const;

// 静态函数 -> 得到本地的当前日期
[static] QDate QDate::currentDate();

6.2. QTime

cpp 复制代码
// 构造函数
QTime::QTime();
/*
    h             ==> must be in the range 0 to 23
    m and s     ==> must be in the range 0 to 59
    ms             ==> must be in the range 0 to 999
*/ 
QTime::QTime(int h, int m, int s = 0, int ms = 0);

// 公共成员函数
// Returns true if the set time is valid; otherwise returns false.
bool QTime::setHMS(int h, int m, int s, int ms = 0);
QTime QTime::addSecs(int s) const;
QTime QTime::addMSecs(int ms) const;

// 示例代码
  QTime n(14, 0, 0);                // n == 14:00:00
  QTime t;
  t = n.addSecs(70);                // t == 14:01:10
  t = n.addSecs(-70);               // t == 13:58:50
  t = n.addSecs(10 * 60 * 60 + 5);  // t == 00:00:05
  t = n.addSecs(-15 * 60 * 60);     // t == 23:00:00

// 从时间对象中取出 时/分/秒/毫秒
// Returns the hour part (0 to 23) of the time. Returns -1 if the time is invalid.
int QTime::hour() const;
// Returns the minute part (0 to 59) of the time. Returns -1 if the time is invalid.
int QTime::minute() const;
// Returns the second part (0 to 59) of the time. Returns -1 if the time is invalid.
int QTime::second() const;
// Returns the millisecond part (0 to 999) of the time. Returns -1 if the time is invalid.
int QTime::msec() const;


// 时间格式化
/*
    -- 时
    h    ==>    The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
    hh    ==>    The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
    H    ==>    The hour without a leading zero (0 to 23, even with AM/PM display)
    HH    ==>    The hour with a leading zero (00 to 23, even with AM/PM display)
    -- 分
    m    ==>    The minute without a leading zero (0 to 59)
    mm    ==>    The minute with a leading zero (00 to 59)
    -- 秒
    s    ==>    The whole second, without any leading zero (0 to 59)
    ss    ==>    The whole second, with a leading zero where applicable (00 to 59)
    -- 毫秒
    zzz    ==>    The fractional part of the second, to millisecond precision, 
            including trailing zeroes where applicable (000 to 999).
    -- 上午或者下午
    AP or A        ==>        使用AM/PM(大写) 描述上下午, 中文系统显示汉字
    ap or a        ==>        使用am/pm(小写) 描述上下午, 中文系统显示汉字
*/
QString QTime::toString(const QString &format) const;

// 阶段性计时
// 过时的API函数
// 开始计时
void QTime::start();
// 计时结束
int QTime::elapsed() const;
// 重新计时
int QTime::restart();

// 推荐使用的API函数
// QElapsedTimer 类
void QElapsedTimer::start();
qint64 QElapsedTimer::restart();
qint64 QElapsedTimer::elapsed() const;


// 操作符重载 ==> 时间比较
bool QTime::operator!=(const QTime &t) const;
bool QTime::operator<(const QTime &t) const;
bool QTime::operator<=(const QTime &t) const;
bool QTime::operator==(const QTime &t) const;
bool QTime::operator>(const QTime &t) const;
bool QTime::operator>=(const QTime &t) const;

// 静态函数 -> 得到当前时间
[static] QTime QTime::currentTime();

6.3. QDateTime

cpp 复制代码
// 构造函数
QDateTime::QDateTime();
QDateTime::QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec = Qt::LocalTime);

// 公共成员函数
// 设置日期
void QDateTime::setDate(const QDate &date);
// 设置时间
void QDateTime::setTime(const QTime &time);
// 给当前日期对象追加 年/月/日/秒/毫秒, 参数可以是负数
QDateTime QDateTime::addYears(int nyears) const;
QDateTime QDateTime::addMonths(int nmonths) const;
QDateTime QDateTime::addDays(qint64 ndays) const;
QDateTime QDateTime::addSecs(qint64 s) const;
QDateTime QDateTime::addMSecs(qint64 msecs) const;

// 得到对象中的日期
QDate QDateTime::date() const;
// 得到对象中的时间
QTime QDateTime::time() const;

// 日期和时间格式, 格式字符参考QDate 和 QTime 类的 toString() 函数
QString QDateTime::toString(const QString &format) const;


// 操作符重载 ==> 日期时间对象的比较
bool QDateTime::operator!=(const QDateTime &other) const;
bool QDateTime::operator<(const QDateTime &other) const;
bool QDateTime::operator<=(const QDateTime &other) const;
bool QDateTime::operator==(const QDateTime &other) const;
bool QDateTime::operator>(const QDateTime &other) const;
bool QDateTime::operator>=(const QDateTime &other) const;

// 静态函数
// 得到当前时区的日期和时间(本地设置的时区对应的日期和时间)
[static] QDateTime QDateTime::currentDateTime();

笔记:

cpp 复制代码
QString & QString :: append (const QString & str)
部分 含义 说明
QString & 返回值类型 返回的是 QString引用,指向调用该函数的对象本身。
QString 类名 表示这个函数属于 QString 类。
:: 作用域解析运算符 表示"属于"的意思,QString::append 表示"这是 QString 类的 append 方法"。
append 函数名 表示这个函数用于在字符串末尾追加内容
(const QString & str) 参数列表 包含一个参数,类型是 const QString&,参数名是 str

详细解析

  1. 返回值 QString &
cpp 复制代码
QString &
  • 表示返回一个 QString 类型的引用

  • 这里的引用指向调用该函数的对象本身 (也就是 this 指向的对象)。

  • 这样设计的好处是支持链式调用,例如:

cpp 复制代码
QString str = "Hello";
str.append(" ").append("World").append("!");   // ✅ 链式调用
// 最终 str = "Hello World!"

因为每次 append 都返回自身的引用,所以可以连续调用。

  1. 类名 QString + 作用域 ::
cpp 复制代码
QString::append
  • 表示 appendQString 类的成员函数,不是全局函数。

  • 如果要调用它,必须通过 QString 对象:

cpp 复制代码
QString s;
s.append("xxx");   // ✅ 正确
append("xxx");     // ❌ 错误!没有指定属于哪个对象
  1. 函数名 append
  • 功能:在字符串末尾追加内容。

  • operator+= 类似,但 append 支持更多参数类型(可以追加 charQCharQStringQByteArray 等)。

  1. 参数 const QString & str
cpp 复制代码
const QString & str
  • const :表示在函数内部不会修改 传入的 str 参数,保证原始数据安全。

  • QString & :表示传递的是引用(地址),而不是拷贝整个对象。

    • 优点:高效,避免复制大字符串的开销。
  • str:参数名,在函数体内代表传入的字符串。

完整使用示例

cpp 复制代码
#include <QString>
#include <QDebug>

int main() {
    QString str = "Hello";

    // 调用 append 成员函数
    QString &ref = str.append(" World");
    // ref 是 str 的引用,指向同一个对象

    qDebug() << str;   // 输出:"Hello World"
    qDebug() << ref;   // 输出:"Hello World"

    // 检查它们是否指向同一个对象
    qDebug() << (&str == &ref);   // 输出:true

    // 链式调用
    str.append(" ").append("from").append(" Qt");
    qDebug() << str;   // 输出:"Hello World from Qt"
}

operator+= 的对比

方法 返回值 示例
append() QString&(支持链式调用) s.append("a").append("b");
operator+= QString&(也支持链式调用) s += "a" += "b";

大多数情况下两者可以互换使用,但 append() 支持更多参数类型(如 QCharcharQByteArray 等),更灵活。

总结:

QString &QString::append(const QString &str)QString 类的成员函数,用于在字符串末尾追加内容,返回自身引用以支持链式调用,参数通过 const 引用传递以避免拷贝,提高性能。

报错:

根本原因(Qt6 + MinGW 高频坑)

正常 Qt Widget 窗口程序(GUI)

  • 不写 CONFIG += console → 链接子系统 =windows,Qt 内置Qt6EntryPoint转换main()WinMain(),正常运行
  • 如果你 pro 文件写了 CONFIG += console 链接器启用 subsystem=console,此时 MinGW 要求入口是标准main(); 但 Qt6 MinGW 环境下存在链接库顺序 BUG,会导致仍然报找不到 WinMain。

需要删除config中的console

相关推荐
冰暮流星2 小时前
javascript之String方法介绍
开发语言·javascript·ecmascript
nianniannnn2 小时前
Qt QMessageBox知识点
开发语言·数据库·qt
故乡de云2 小时前
AWS 添加付款方式失败排查清单:卡片、银行风控与账号状态逐项定位
开发语言·php
J_yyy3 小时前
【Qt核心组件类框架】
开发语言·qt
运维行者_3 小时前
如何查看每个IP的带宽使用情况?NetFlow 技术实战指南
开发语言·网络·分布式·后端·架构·带宽
天天进步20153 小时前
Python全栈项目--基于深度学习的图像超分辨率系统
开发语言·python·深度学习
blevoice3 小时前
抖抖燃脂机单 AC6966B 主控调试踩坑:Type-C 整机供电喇叭无声排障
c语言·开发语言·单片机
小小晓.4 小时前
C++小白记:C风格字符串和数组用法
c语言·开发语言·c++
Helen_cai4 小时前
OpenHarmony 项目统一全局样式、尺寸、色彩主题封装 ThemeUtil(API23)
开发语言·前端·javascript·华为·harmonyos