Qt常用类 - QDir
今天发博客晚了,因为下午临时被领导叫去加班,也是刚刚回来,虽然比较辛苦,还受了点小伤,把手给划破了,但是好久没这么淋漓尽致的加个大班了,呵呵,痛并快乐着吧…
这篇博客发布后,需要待审核,还算是今天(2019.5.4)写的吧,毕竟审核这事我也控制不了啊!
1 开发环境
在介绍内容之前,先说明一下开发环境,如下图:
Qt版本:Qt5.3.2;
Qt开发工具:Qt Creater 3.2.1;
Qt构建工具:Desktop Qt 5.3 MinGW 32bit;
Qt开发平台:Windows 7 64bit。
2 QDir
QDir是Qt中用到的目录操作类,可以对目录进行查找、设置、获取等操作。首先,将QDir中的常用接口整理出来,分为初始化、设置和获取、判断、创建和删除、获取当前应用程序路径共5类,这样方便学习和理解。
//初始化
QDir(const QDir &dir);
QDir(const QString &path = QString());
//设置和获取
static QDir QDir::current();
static QString QDir::currentPath();
static bool setCurrent(const QString &path);
QString path() const;
//判断
bool exists(const QString &name) const
bool exists() const;
//创建和删除
bool mkdir(const QString &dirName) const;
bool rmdir(const QString &dirName) const;
//获取当前应用程序路径
static QString QCoreApplication::applicationDirPath();
static QString QCoreApplication::applicationFilePath();
下面,是上述接口的使用例程。
#include <QDir>
#define qPrintableU8(_string) (QString(_string).toUtf8().constData())
//QDir(const QDir &dir);
//QDir(const QString &path = QString());
QDir dirNull;
QDir dirConstruct("C:/");
qDebug("dirNull = %s", qPrintableU8(dirNull.path()));
qDebug("dirConstruct = %s", qPrintableU8(dirConstruct.path()));
//static QDir QDir::current();
//static QString QDir::currentPath();
//static bool setCurrent(const QString &path);
//QString path() const;
QDir dirWork = QDir::current();
qDebug("dirWork = %s", qPrintableU8(dirWork.path()));
QDir::setCurrent("D:/");
qDebug("currentPath set to %s", qPrintableU8(QDir::currentPath()));
//bool exists(const QString &name) const
//bool exists() const;
QDir dirExist("C:/myDir1");
qDebug("C:/myDir1 is exist? %d", dirExist.exists());
qDebug("%s/myDir1 is exist? %d", qPrintableU8(dirWork.path()), dirWork.exists("myDir1"));
//bool mkdir(const QString &dirName) const;
//bool rmdir(const QString &dirName) const;
if (!dirWork.exists("myDir2")) { dirWork.mkdir("myDir2"); }
if (dirWork.exists("myDir1")) { dirWork.rmdir("myDir1"); }
//static QString QCoreApplication::applicationDirPath();
//static QString QCoreApplication::applicationFilePath();
qDebug("QCoreApplication::applicationDirPath() = %s", qPrintableU8(QCoreApplication::applicationDirPath()));
qDebug("QCoreApplication::applicationFilePath() = %s", qPrintableU8(QCoreApplication::applicationFilePath()));
在学习过程中,可以将上述代码放到一个按钮的响应函数中,以调试方式运行,就可以在Qt Creater中的应用程序输出窗口看到输出结果了。