QT常用工具类函数封装汇总

**

更新时间:2021-12-06

**

对于一个懒人+健忘症,肯定是把所有常用的函数使用方法记录到小本本上,到时候直接ctrl+f查找使用。哈哈哈

下面我给一些比较常用到的封装函数给大家参考。
(主要都是给自己看的)

1.//获取当前时间

所需头文件:
#include < QDateTime>

QString getdate()
{
    QDateTime current_date_time = QDateTime::currentDateTime();
    QString date = current_date_time.toString("yyyy-MM-dd hh:mm::ss.zzz");
    qDebug()<<date;
    return date;
}

2.//读取本地配置文件信息–以mysql数据库为例

所需头文件:
#include < QSettings>

QSettings *configIni=new QSettings("./debug/config.ini",QSettings::IniFormat);
QString address=configIni->value("MysqlMsg/address").toString();
QString account =configIni->value("MysqlMsg/account").toString();
QString password =configIni->value("MysqlMsg/password").toString();
QString dbname =configIni->value("MysqlMsg/dbname").toString();
int port  =configIni->value("MysqlMsg/port").toInt();
delete configIni;//读取完成删除指针

路径和名称什么的自己修改

3.//分割字符串

所需头文件:
#include < QList>

QString str="123;456;";
QStringList fgMsg=str.split(";");
QString str2=fgMsg.at(0);

4.//获取本机mac地址

所需头文件:
#include < QNetworkInterface>

QString getmacaddress()
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址,则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    return strMacAddr;

}

根据当前网口名,通过配置进行筛选,获取对应的网口mac物理地址
macType为配置文件的网口名称
(适用于双网卡的服务器)

//获取mac地址
QString getMacAddress()
{
//    qDebug()<<"macType:"<<macType;
    QString mac;
    QList<QNetworkInterface> network = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface i, network)
    {
        QString netName = i.humanReadableName();
//        qDebug()<<"netName:"<<netName;
        if(netName.compare(macType) == 0)
        {
            mac=i.hardwareAddress();
            mac.replace(":","-");

//            qDebug()<<"mac:"<<i.hardwareAddress();
        }
    }
    return mac;
}

5.获取时间戳(毫秒级)

所需头文件:
#include < QDateTime>
2种:

qint64 getunixtime()
{
	QString timestamp = QString::number(QDateTime::currentMSecsSinceEpoch());
	qint64 time= timestamp.toLongLong();
	return time;
}
QString getunixtime()
{
	QString timestamp = QString::number(QDateTime::currentMSecsSinceEpoch());
	return timestamp;
}

6.读取本地图片为base64位图片

所需头文件:
pro文件添加QT += gui
#include < QImage>
#include < QBuffer>

QString pictoBase64(const QString & imgPath)
{
	QImage image(imgPath);
	QByteArray ba;
	QBuffer buf(&ba);
	image.save(&buf, "jpg");
	QByteArray hexed = ba.toBase64();
	buf.close();
	QString basepic = hexed;
	return basepic;
}

7.获取当前exe的路径

所需头文件:
#include < QCoreApplication>

    QString execurrentPath = QCoreApplication::applicationDirPath();
    qDebug()<<"execurrentPath"<<execurrentPath;

8.单次和多次执行的定时器使用

所需头文件:
#include < QTimer>

//单次执行定时器
//定时时间-对象-执行的槽函数
//lamdba
		QTimer::singleShot(  1000, this, [=] {
			//想要执行的代码		
		});
QTimer::singleShot( 1000, this,SLOT(printMsg());

//多次执行定时器
        timer= new QTimer();
        connect(timer, SIGNAL(timeout()), this, SLOT(槽函数名()));
        timer->start(60 * 1000);//1min
        
		timer->stop();	//停止定时器
		delete timer;	//删除定时器指针


9.打印中文

所需头文件:
#include < QDebug>

	qDebug()<<QString::fromLocal8Bit("中文");

10.判断两个QString是否相等

QString str = QString::fromLocal8Bit("球形");
QString str2;
if(str.compare(QString::fromLocal8Bit("球形") == 0)

if(str.compare(str2) == 0)
 
或者:
if(str ==QString::fromLocal8Bit("球形"))
{
 
}

11.QProcess调用cmd命令–重启关闭电脑

所需头文件:
#include < QProcess >


    QProcess p;
    p.start("shutdown -r -t 10");//10s重启电脑
    p.start("shutdown -s -t 10");//10s关闭电脑
    p.waitForStarted();
    p.waitForFinished();
    qDebug()<<QString::fromLocal8Bit(p.readAllStandardOutput());

12.QString字符串查找子字符串

Qt::CaseSensitive 字符大小写敏感(字母分大小写)
Qt::CaseInsensitive 无大小写敏感 (字母不分大小写)

    QString aa="abc你好";
    if (aa.contains("你好", Qt::CaseSensitive))
    {
        qDebug()<<"123";
    }

13.获取本地文件夹里所有文件名

QStringList Widget::getLocalFilePicName(QString path)
{
    QStringList fileNameList;
    QFileInfoList list;
    //判断路径是否存在
    QDir dir(path);
    if(!dir.exists())
    {
        QMessageBox::about(NULL,"tip", "not exist:");
    }else{
        //查看路径中后缀为.cfg格式的文件
        QStringList filer;
        filer << "*.jpg" <<"*.png";//设定需要的文件类型(*为所有类型)
        list = dir.entryInfoList(filer);
        //qDebug()<<"file path:"<<list;
        //get file path
        for(int i=0;i<list.size();i++)
        {
            fileNameList<<list.at(i).filePath();
        }

        //get file name
        //        for(int i=0;i<list.size();i++)
        //        {
        //            fileNameList<<list.at(i).fileName();
        //        }
        //        qDebug()<<"file name:"<<fileNameList;
    }

    return fileNameList;

}

14.sleep线程睡眠msec

/*
    函数名:sleep()
    参   数: msec - 单位为毫秒
    描   述: 延时功能
*/
#include <QTime>
bool sleep(unsigned int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);

    while (QTime::currentTime() < dieTime)
    {
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }

    return true;
}

持续更新~

不得不说,qt的强大功能真的是太舒服了。
提供了很多常用的方法,不需要再自己写了。

  • 3
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
m_pDbProcPic = new CDBProcess("sqlserver"); m_pDbProc->openDB("mysvr", "mydb", "myusername", "mypwd"); m_pDbProcPic = new CDBProcess("mysql"); m_pDbProc->openDB("localhost", "mydb", "root", "password"); m_pDbProcPic = new CDBProcess("access"); m_pDbProc->openDB("", strMDB, "sa", "password"); m_pDbProcPic = new CDBProcess("sqlite"); m_pDbProcPic->openDB("", "mysqlitedb"); CDBProcess使用说明 构造函数: CDBProcess(const QString strType); 参数:为数据库类型,不区分大小写,支持的类型有 sqlite mysql access sqlserver 例: CDBProcess db("sqlite"); -------------------------------------------------- 打开数据库 bool openDB(const QString strSvrName, //服务器名 const QString strDBname, //数据库名 const QString strUserID="", //用户名 const QString strUserPwd=""); //密码 打开数据库成功,返回true,否则返回false 对于sqlite,只有strDBname有效,其它参数忽略,如db.openDB("", "mysqlite.db") 对于MS Access数据库,strSvrName为空,用户名默认为"sa",如db.openDB("", "myaccess.mdb"); 对MSAccess数据库,也可通过一个UDL文件,打开,如db.openDB("my.udl", ""); mysql和sqlserver,就是各个参数依次提供,如db.openDB("svr1", "mydb", "user1", "abcd"); ----------------------------------------------------- 关闭数据库,CDBProcess析构时,亦会自动关闭数据库 void closeDB(); //db.closeDB(); ------------------------------------------------------ 执行Sql语句 bool excuteSQL(const QString); ------------------------------------------------------- 打开记录集 bool openRecordsetBySql(const QString strSql, //Sql语句 int idx = -1); //记录集id,用于标识记录集,默认值为-1 例: db.openRecordsetBySql("SELECT * FROM TB1", 5); 打开一个记录集,标识号为5,后面操作这个记录集,也要提供这个标识号 -------------------------------------------------------- 关闭记录集 void closeRecordset(int idx = -1); 例: db.closeRecordset(5); 关闭之前打开的标识为5的记录集 ----------------------------------- 数据库是否处在打开状态 bool isOpen() const; ------------------------------------ 记录集游标是否在结尾,参数为记录集标识 bool recEOF(int idx = -1) const; 例:bool b = db.RecBOF(5); ------------------------------------ 记录集游标是否在第一条记录之前,参数为记录集标识 bool recBOF(int idx = -1) const; ---------------------------------------- 删除一个表 bool dropTable(const QString); --------------------------------------------- 读取标识为idx记录集的当前记录的各字段值,方法如示例: bool getFieldsValueFromRec(int idx, const char* szFldInfo, ...) const; int iSN; QString strName; double dHeight; QDateTime dt; QByteArray ba; db.getFieldsValueFromRec(5, //记录集id "sn%d", &iSN, //字段名加类型 sn为字段名%d表示整型,&iSN传入指针,保存返回字段值 "name%s", &strName, //字段名加类型 name为字段名%s表示字符串(QString) "height&f", &dHeight, //字段名加类型 height为字段名%f表示小数(double) "birthday%t", &dt, //字段名加类型 birthday为字段名%t表示时间(QDateTime) "photo%b", &ba, //字段名加类型 photo为字段名%b表示二进制流(QByteArray) CDBProcess::szEnd); //结束标志,"|" 执行后,各字段值就保存在iSN, strName等变量中了。 参数:第一个参数为记录集id 后面可变参数,字段%类型标识,用于保存返回值的指针, 类型标识:%d-int %s-QString %f-double %t-QDateTime %b-QByteArray --------------------------------------------------------------------------- 向一个数据表中填加一条记录 bool addFieldsValueToTbl(const QString strTbl, const char* szFldInfo, ...); 参数:第一个参数strTbl,为表名 后面是可变参数,为"字段%类型标识",值(或指针),注int,double类型直接传值,其它传指针 例: db.addFieldsValueToTbl("TB1", //表名 "sn%d", iSN, //字段名加类型 sn为字段名%d表示整型,iSN传入值 "name%s", &strName, //字段名加类型 name为字段名%s表示字符串(QString), 传入QString变量指针 "height&f", dHeight, //字段名加类型 height为字段名%f表示小数(double),dHeight传入值 "birthday%t", &dt, //字段名加类型 birthday为字段名%t表示时间(QDateTime),传入指针 "photo%b", &ba, //字段名加类型 photo为字段名%b表示二进制流(QByteArray),传入指针 CDBProcess::szEnd); //结束标志,"|" ----------------------------------------------------------- 修改表中符合WHERE子句条件的记录 bool updateTblFieldsValue(const QString strTbl, QString strWhere, const char * szFldInfo, ... ); strTbl表名 strWhere SQL WHERE子句,如"WHERE sn=20" const char * szFldInfo, ...可变参数,同addFieldsValueToTbl 例: db.updateTblFieldsValue("TB1", "WHERE sn=20", "height&f", dHeight, "photo%b", &ba, CDBProcess::szEnd); ---------------------------------------------------------------- 以下几个函数分别是获取记录数,和记录光标移动。参数为记录集标识 long getRecordCount(int idx = -1) const; bool moveFirst(int idx = -1) const; bool movePrevious(int idx = -1) const; bool moveNext(int idx = -1) const; bool moveLast(int idx = -1) const; bool moveTo(int n, int idx = -1) const; -------------------------------------------------------------------- 返回数据库名 QString getDbName() const; ------------------------ 以下几个函数未验证 bool execStoreProcOfArgList(int idx, const QString strStoreProc, const char* szFldsInfo, ...); bool exexProc(const QString strStoreProc, QString str1, QString& str2); bool transaction(); bool commit(); bool rollback();
Qt是一种广泛应用的C++跨平台开发框架,它为开发人员提供了丰富的工具和类库来简化软件开发过程。Qt还提供了对数据库的支持,允许开发者使用数据库进行数据的存储和管理。为了进一步简化开发过程,我们可以封装一个数据库工具类数据库工具类的主要目的是封装数据库的操作,使其易于使用、可重用,并提供错误处理和异常处理机制。以下是一个可能的Qt数据库工具类的实现示例。 首先,我们需要一个类来代表数据库连接。我们可以创建一个名为Database的类,其中包含连接数据库、断开数据库、执行查询等功能的成员函数。 其次,我们可以创建一个Table类,用于代表数据库中的表。Table类可以提供一些功能,如创建表、插入数据、更新数据、删除数据等。 我们还可以为每个表创建对应的模型类,用于与Qt的模型视图框架进行交互。模型类可以继承自Qt的QAbstractTableModel类,并实现一些必要的函数,如rowCount、columnCount、data等。这样,我们可以方便地将表中的数据展示在Qt的ListView或TableView等控件上。 在封装数据库工具类时,我们还可以考虑使用单例模式,确保整个应用程序中只有一个数据库实例存在。这样做可以避免重复创建数据库连接和占用过多资源。 总的来说,Qt数据库工具类封装可以大大简化数据库操作的编写过程,提高代码的可读性和可维护性。通过对数据库连接的封装,我们可以更方便地进行数据库操作,同时减少错误和异常处理的工作量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值