五、常用类
1. QString字符串类(掌握)
QString是Qt框架的Unicode字符串类,采用UTF-16编码,每个字符为16位QChar。相比C++的std::string
,其优势在于:
-
跨平台兼容性:自动处理不同编码转换
-
高效操作:内置丰富API(查找/替换/格式化)
-
内存安全:隐式共享机制减少内存拷贝
核心API示例:
// 类型转换
QString str = QString::number(255, 16); // "ff"
bool ok;
int num = str.toInt(&ok); // 255 (ok=true)
// 字符串操作
QString s1 = "Qt";
QString s2 = "框架";
QString combined = s1 + " " + s2; // "Qt 框架"
中文处理建议:
-
文件编码统一为UTF-8
-
使用
QStringLiteral
宏处理编译时常量字符串 -
参考编码规范文档:腾讯网页链接
常用API速查:
功能 | 函数示例 |
---|---|
整数转字符串 | QString::number(255, 16) |
字符串转整数 | str.toInt(&ok) |
字符串拼接 | QString("%1%2").arg(a).arg(b) |
截取子串 | str.mid(2, 3) |
大小写转换 | str.toUpper() / str.toLower() |
2. 容器类(掌握)
Qt容器类优化自STL,具有更优的内存管理和跨平台特性,支持隐式共享和线程安全读取。
2.1 顺序容器 - QList
特性:
-
动态数组实现,支持快速头尾操作
-
隐式共享(写时复制)
-
线程安全(只读时多线程安全)
自定义类型存储示例:
// Student类定义
class Student {
public:
Student(int id, QString name) : m_id(id), m_name(name) {}
int getId() const { return m_id; }
QString getName() const { return m_name; }
private:
int m_id;
QString m_name;
};
// 容器操作
QList<Student> students;
students << Student(1, "张三") << Student(2, "李四");
students.insert(1, Student(3, "王五")); // 插入到索引1位置
students.removeAt(0); // 删除第一个元素
2.2 关联容器 - QMap类
特性:
-
键值对存储,按键自动排序
-
哈希表实现(QHash更快但无序)
-
支持多值映射(QMultiMap)
键值操作示例:
QMap<QString, QString> config;
config.insert("host", "127.0.0.1");
config.insert("port", "8080");
// 批量操作
QMap<QString, QString> newConfig = config;
newConfig["timeout"] = "30";
// 迭代访问
for(auto it = config.begin(); it != config.end(); ++it) {
qDebug() << it.key() << ":" << it.value();
}
3. Qt数据类型系统
3.1 跨平台数据类型
Qt类型 | 对应C++类型 | 说明 |
---|---|---|
quint8 |
uint8_t | 无符号8位整数 |
qint32 |
int32_t | 有符号32位整数 |
qreal |
double | 高精度浮点数 |
3.2 QVariant统一变量类(熟悉)
多态数据容器:
QVariant var = 42;
var = QString("Hello");
var = QDateTime::currentDateTime();
// 类型检查与转换
if(var.canConvert<QString>()) {
QString str = var.toString();
}
3.3 QStringList字符串列表
字符串列表操作:
QStringList list = {"Qt", "C++", "GUI"};
list << "Framework"; // 添加元素
list.removeAll("C++"); // 删除所有匹配项
4. 时间与日期处理(掌握)
4.1 QDateTime类
核心功能:
// 获取当前时间
QDateTime now = QDateTime::currentDateTime();
// 时间格式化
QString formatted = now.toString("yyyy-MM-dd hh:mm:ss.zzz");
// 时间戳操作
qint64 ms = QDateTime::currentMSecsSinceEpoch(); // 毫秒级时间戳
// 时间计算
QDateTime future = now.addDays(7); // 7天后
4.2 时间测量
QElapsedTimer timer;
timer.start();
// 执行耗时操作
for(int i=0; i<1000000; ++i) {}
qint64 elapsed = timer.elapsed(); // 毫秒级耗时
5. QTimer定时器类(重点)
实现周期性任务:
class Worker : public QObject {
Q_OBJECT
public slots:
void doWork() {
static int count = 0;
qDebug() << "Tick:" << ++count;
if(count >= 10) emit finished();
}
signals:
void finished();
};
// 使用示例
QTimer *timer = new QTimer(this);
Worker *worker = new Worker();
connect(timer, &QTimer::timeout, worker, &Worker::doWork);
connect(worker, &Worker::finished, timer, &QTimer::deleteLater);
timer->start(1000); // 每秒触发
关键特性:
-
支持单次/周期性触发
-
精度受系统调度影响(通常±50ms)
-
跨线程需使用
moveToThread
附:完整代码示例
QTimer完整实现:
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QTimer>
#include <QDateTime>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
private:
Ui::Dialog *ui;
QTimer *timer;
private slots:
void timeOutSlot();
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
timer = new QTimer(this);
// 提前刷新显式控件
timeOutSlot();
// 设置timer的参数
timer->setInterval(500); // 设置时间间隔
timer->setSingleShot(false); // 设置为周期任务
connect(timer,SIGNAL(timeout()),
this,SLOT(timeOutSlot()));
// 启动定时器
timer->start();
}
Dialog::~Dialog()
{
if(timer->isActive()) // 如果正在运行,则先关闭
{
timer->stop();
}
delete timer;
delete ui;
}
void Dialog::timeOutSlot()
{
// 获取当前系统时间,转换为:时:分:秒。返回值为QString字符串
QString str = QDateTime::currentDateTime().toString("hh:mm:ss");
ui->lcdNumber->display(str);
}