简述
在项目中,有些方法是经常要用的。如果没有一个公共的地方来放置这些方法,就有可能,在每次使用的时候都需要重新编写一次,导致相同或者类似的方法散落在工程中的每一个角落。需要修复bug时,就到处取寻找,然后把每一个方法都修改一遍,浪费大量的时间,所以我在这个工程中建立了一个命名空间,专门放置这些方法。
共享库
在多工程项目中添加一个名为MyShareLibrary
的动态共享库子项目,添加完成后,多工程文件ToolBox.pro
内容如下:
TEMPLATE = subdirs
CONFIG += ordered
SUBDIRS += \
MyShareLibrary
修改MyShareLibrary.pro
文件如下:
QT += widgets
TARGET = MyShareLibrary
TEMPLATE = lib
DEFINES += MYSHARELIBRARY_LIBRARY
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
myassistant.cpp
HEADERS += \
myassistant.h \
DESTDIR = ../bin
DESTDIR
指定目标文件生成的目录
myassistant.h
#ifndef MYASSISTANT_H
#define MYASSISTANT_H
#include <QFile>
#include <QString>
//MyAssistant
namespace My {
/*
* func: 获取系统时间
* format: 时间格式
* return: 返回对应格式的系统时间字符串
*/
QString getCurentTime(const QString &format = "yyyy-MM-dd hh:mm:ss");
/*
* func: 读取文件数据
* name: 待读取的文件路径名
* data: 引用,将读取的数据赋值于该引用
* return: 读取成功返回 true, 失败返回 false
*/
bool readFile(const QString &name, QString &data);
/*
* func: 读取文件数据
* name: 待读取的文件路径名
* return: 返回读取出来的数据
*/
QString readFile(const QString &name);
/*
* func: 写入数据至文件,当路径或文件不存在时,自动创建
* name: 待写入的文件路径名
* data: 待写入的数据
* flags: 文件打开方式
* return: 写入成功返回true, 失败返回 false
*/
bool writeFile(const QString &name,
const QByteArray &data,
const QIODevice::OpenMode flags = QIODevice::WriteOnly|QIODevice::Text);
/*
* func: 追加数据至文件,当路径或文件不存在时,自动创建
* name: 待写入的文件路径名
* data: 待写入的数据
* return: 写入成功返回true, 失败返回 false
*/
bool appendFileData(const QString &name, const QByteArray &data);
}
#endif // MYASSISTANT_H
myassistant.cpp
#include "myassistant.h"
#include <QDir>
#include <QFile>
#include <QDebug>
#include <QFileInfo>
#include <QDateTime>
#include <QMessageBox>
#include <QTextStream>
bool My::readFile(const QString &name, QString &data)
{
QFile file(name);
if(!file.exists()) {
return false;
}
if(!file.open(QFile::ReadOnly)) {
QMessageBox::critical(NULL, "提示", QString("%1: %2").arg("读取失败", name));
file.close();
return false;
}
QTextStream in(&file);
data = in.readAll();
file.close();
return true;
}
QString My::readFile(const QString &name)
{
QString buf;
readFile(name, buf);
return buf;
}
bool My::writeFile(const QString &name, const QByteArray &data, const QIODevice::OpenMode flags)
{
QFileInfo fileInfo(name);
QString path = fileInfo.path();
if(!QFile::exists(path)) {
if(! QDir().mkpath(path)) {
QMessageBox::critical(NULL, "提示", QString("%1: %2").arg("无法创建文件夹", path));
}
}
QFile file(name);
if ( !file.open(flags)) {
QMessageBox::critical(NULL, "提示", QString("%1: %2").arg("无法创建文件", name));
}
QTextStream out(&file);
out << data ;
out.flush();
file.close();
return true;
}
bool My::appendFileData(const QString &name, const QByteArray &data)
{
return writeFile(name, data, QIODevice::WriteOnly|QIODevice::Text|QIODevice::Append);
}
QString My::getCurentTime(const QString &format)
{
return QDateTime::currentDateTime().toString(format);
}
以上就是命名空间My
的全部内容了(对于这个命名空间定义为My
,纯粹是因为这个单词好看,就如大家喜欢这样子写Qt
, 我也喜欢这样子写My
),后期会根据需要扩展这个库,现在只写了最基础的部分。