一些自定义函数

1、每两个字符加一个空格

QString MainWindow::AddSpaceToStr(QString source_str)

{

  QString result_str = "";//返回带有空格的字符串

  int source_str_length = source_str.length();

  for(int i=0;i<source_str_length;i++)

  {

    result_str += source_str.mid(i,2);

    result_str += " ";

    i++;

  }

  return result_str;

}

2、将QString转化到QByteArray里面//此方法不适用,其实有更好的方法

QByteArray MainWindow::StrToHex(QString packet_str,QByteArray dataArray)
{
    int dataCount = 0;//字节数组地址
    int packetLength = packet_str.length();//发送内容的字符数
    int dataLength = 0;//字节数组的长度
    dataLength = packetLength/2;//字符数除以2
    if(packetLength%2 != 0)//如果为奇数
        dataLength++;
    dataArray.resize(dataLength);//设置字节数组的长度
    QString tempStr = "";
    for(int i=0;i<packetLength;i++)//通过此循环将发送内容每两个字符转化为一个字节十六进制,存在字节数组里面
    {
        bool ok;
        tempStr = packet_str.mid(i,2);
        dataArray[dataCount++] = (uchar)tempStr.toInt(&ok,16);
        i++;
    }
return dataArray;
}

QString dataStr = ui->textEdit->toPlainText();

 

dataStr = dataStr.replace(" ","");

 

QByteArray ba = QByteArray::fromHex(dataStr.toLatin1());


3、QString转const char
#include <iostream>//需要使用std
QString tempFileName;

   std::string str = tempFileName.toStdString();//标准库的string

 

 const char* ch = str.c_str();//ch就是const char

4、获取时间格式:年-月-日-时-分-秒 

QTime currentTime = QTime::currentTime();

QString timeStr = "--->" + QString::number(currentDate.year()) + "-";//年

timeStr += QString::number(currentDate.month()) + "-";//月

timeStr += QString::number(currentDate.day()) + "-";//日

timeStr += QString::number(currentTime.hour()) + "-";//时

timeStr += QString::number(currentTime.minute()) + "-";//分

timeStr += QString::number(currentTime.second());//秒

 

QDateTime current_date_time = QDateTime::currentDateTime();
QString current_date = current_date_time.toString("yyyy-MM-dd");
QString current_time = current_date_time.toString("hh:mm:ss.zzz ");
 
5、字符数组转十六进制字符串char{0x00,0x01}->QString(00 01)
QString MyMethod::uchar2Str(uchar *sourceChar, int length)
{  
QByteArray ba;ba.resize(length);  
memcpy(ba.data(),sourceChar,length);  
QString resultStr = ba.toHex();  
resultStr = MyMethod::formatStr(resultStr);  
return resultStr;
}
 
6、打印CAN错误码
void MainWindow::printCanErrCode()
{
QString tempStr;VCI_ERR_INFO err_info;
VCI_ReadErrInfo(this->DevType,this->DevIndex,this->CanIndex,&err_info);
tempStr = QString::number(err_info.ErrCode);
QMessageBox::warning(this,"打开设备","操作失败\n错误代码:"+tempStr);
7、设置本地的QSS文件
QString MainWindow::getQssContent()
{  
QFile styleSheet("F:\\QtSpace\\MyCanTest\\test.txt");  
if (!styleSheet.open(QIODevice::ReadOnly))  
{    
qDebug()<<"Can't open the style sheet file.";   
 return "";  
}  
return styleSheet.readAll();}
8、根据5个串口配置combobox,获取串口配置结构体1)、串口配置结构体定义
typedef struct
{
    QString portName;//串口号
    QSerialPort::BaudRate baudRate;//波特率
    QSerialPort::DataBits dataBits;//数据位
    QSerialPort::Parity parity;//校验位
    QSerialPort::StopBits stopBites;//停止位
}SerialportInfo;
2)、根据5个combobox返回此结构体
SerialportInfo MainWindow::getSerialportInfo(QComboBox* cb1,QComboBox* cb2,QComboBox* cb3,QComboBox* cb4,QComboBox* cb5)
{
    SerialportInfo serialPortInfo;
    /*串口名字*/
    serialPortInfo.portName = cb1->currentText();//串口名字
    /*波特率*/
    if("1200"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud1200;
    }
    else if("2400"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud2400;
    }
    else if("4800"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud4800;
    }
    else if("9600"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud9600;
    }
    else if("19200"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud19200;
    }
    else if("38400"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud38400;
    }
    else if("57600"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud57600;
    }
    else if("115200"==cb2->currentText())
    {
        serialPortInfo.baudRate = QSerialPort::Baud115200;
    }
    /*数据位*/
    if(0==cb3->currentIndex())
    {
        serialPortInfo.dataBits = QSerialPort::Data8;
    }
    else if(1==cb3->currentIndex())
    {
        serialPortInfo.dataBits = QSerialPort::Data7;
    }
    else if(2==cb3->currentIndex())
    {
        serialPortInfo.dataBits = QSerialPort::Data6;
    }
    else if(3==cb3->currentIndex())
    {
        serialPortInfo.dataBits = QSerialPort::Data5;
    }
    /*校验位*/
    if("NONE"==cb4->currentText())
    {
        serialPortInfo.parity = QSerialPort::NoParity;
    }
    else if("ODD"==cb4->currentText())
    {
        serialPortInfo.parity = QSerialPort::OddParity;
    }
    else if("EVEN"==cb4->currentText())
    {
        serialPortInfo.parity = QSerialPort::EvenParity;
    }
    else if("MARK"==cb4->currentText())
    {
        serialPortInfo.parity = QSerialPort::MarkParity;
    }
    else if("SPACE"==cb4->currentText())
    {
        serialPortInfo.parity = QSerialPort::SpaceParity;
    }
    /*停止位*/
    if(0==cb5->currentIndex())
    {
        serialPortInfo.stopBites = QSerialPort::OneStop;
    }
    else if(1==cb5->currentIndex())
    {
        serialPortInfo.stopBites = QSerialPort::OneAndHalfStop;
    }
    else if(2==cb5->currentIndex())
    {
        serialPortInfo.stopBites = QSerialPort::TwoStop;
    }
    return serialPortInfo;
}
9、QString("FF")转BYTE(FF)
BYTE MyMethod::hexToByte(QString info)
{
    return (BYTE)info.toUInt(NULL,16);
}
10、根据年月日得到是否为工作日
int CaculateWeekDay(int y, int m, int d)
{
    if(m==1||m==2) //把一月和二月换算成上一年的十三月和是四月
    {
        m+=12;
        y--;
    }
    int Week=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
    switch(Week)
    {
    case 0:
        return WORKDAY;/*cout << "是星期一" << endl;*/ break;
    case 1:
        return WORKDAY;/*cout << "是星期二" << endl;*/ break;
    case 2:
        return WORKDAY;/*cout << "是星期三" << endl;*/ break;
    case 3:
        return WORKDAY;/*cout << "是星期四" << endl;*/ break;
    case 4:
        return WORKDAY;/*cout << "是星期五" << endl;*/ break;
    case 5:
        return NOTWORKDAY;/*cout << "是星期六" << endl;*/ break;
    case 6:
        return NOTWORKDAY;/*cout << "是星期日" << endl;*/ break;
    default:return ERRORDAY;
    }
    return ERRORDAY;
}

 11、从数据流中找出数据包

   static QByteArray allBa;//用来存所有文件
    allBa.append(tcpClient->readAll());//读取数据
    int head = allBa.indexOf(HEAD);//报文头的位置
    uint16_t length = 0;//存长度字节
    QByteArray currentBa;
    int id = 0;
    while (-1 != head)
    {
        allBa = allBa.mid(head);//去掉报头之前的
        memcpy(&length, allBa.data() + 2, 2);
        if (allBa.size() >= length)//长度够,进行解析
        {
            currentBa = allBa.mid(0, length);//获取当前完成包
            id = Mymethod::getPacketType(currentBa);
            if (-1 != id)
            {
                emit getPacketSignal(id, currentBa);
                qDebug() << "接收指令:" << currentBa.toHex().toUpper();
            }
       allBa = allBa.mid(length);
} else { break; } head = allBa.indexOf(HEAD);//刷新报文头的位置 }

 12、获取随机字符串

void Mysqltool::setRandString(QString & randString)
{
    int max = 8;
    QString tmp = QString("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ");
    QString str;
    QTime t;
    t= QTime::currentTime();
    qsrand(t.msec()+t.second()*1000);
    for(int i=0;i<max;i++)
    {
        int ir = qrand()%tmp.length();
        str[i] = tmp.at(ir);
    }
    randString = str;
}

 13、判断一个值是否在一个范围内,范围用字符串表示

范围示例:

 

 

bool Mymethod::isValueInRange(float value, QString rangeStr)
{
    bool ret = false;
    if(rangeStr=="[0.5,0.7)|(1.3,1.5]")
    {
        qDebug()<<"test";
    }
    //布尔判断
    if(!rangeStr.contains("(") && !rangeStr.contains("[") && !rangeStr.contains(",") && !rangeStr.contains("|"))
    {
        if(rangeStr.toDouble() == value)
        {
            ret = true;
        }
    }
    //判断枚举
    else if(!rangeStr.contains("(") && !rangeStr.contains("[") && rangeStr.contains(","))
    {
        QString str = QString::number(value);
        if(rangeStr.contains(str))
        {
            ret = true;
        }
    }
    //判断单区间
    else if((rangeStr.contains("(") || rangeStr.contains("[")) && rangeStr.contains(",") && !rangeStr.contains("|"))
    {
        QString left, right;//[342,418]
        if(rangeStr.contains("(") && rangeStr.contains(")"))
        {
            int pos = rangeStr.indexOf(",");
            left = rangeStr.left(pos).remove("(");
            right = rangeStr.remove(0, pos+1).remove(")");
            if(left == "~" && right == "~")
            {
                ret = true;
            }
            else if(left == "~" && right != "~")
            {
                if(value < right.toDouble())
                {
                    ret = true;
                }
            }
            else if(left != "~" && right == "~")
            {
                if(value > left.toDouble())
                {
                    ret = true;
                }
            }
            else
            {
                if(value > left.toDouble() && value < right.toDouble())
                {
                    ret = true;
                }
            }
        }
        if(rangeStr.contains("[")&&rangeStr.contains("]"))
        {
            int pos = rangeStr.indexOf(",");
            left = rangeStr.left(pos).remove("[");
            right = rangeStr.remove(0, pos+1).remove("]");
            if(value >= left.toDouble() && value <= right.toDouble())
            {
                ret = true;
            }
        }
        if(rangeStr.contains("(")&&rangeStr.contains("]"))
        {
            int pos = rangeStr.indexOf(",");
            left = rangeStr.left(pos).remove("(");
            right = rangeStr.remove(0, pos+1).remove("]");
            if(left == "~" && right != "~")
            {
                if(value <= right.toDouble())
                {
                    ret = true;
                }
            }
            else if(left != "~" && right != "~")
            {
                if(value > left.toDouble() && value <= right.toDouble())
                {
                    ret = true;
                }
            }
        }
        if(rangeStr.contains("[")&&rangeStr.contains(")"))
        {
            int pos = rangeStr.indexOf(",");
            left = rangeStr.left(pos).remove("[");
            right = rangeStr.remove(0, pos+1).remove(")");
            if(left != "~" && right == "~")
            {
                if(value >= left.toDouble())
                {
                    ret = true;
                }
            }
            else if(left != "~" && right != "~")
            {
                if(value >= left.toDouble() && value < right.toDouble())
                {
                    ret = true;
                }
            }
        }
    }
    // 判断多区间
    else if(rangeStr.contains("|"))
    {
        QString left;
        QString l_left, l_right;
        int pos = rangeStr.indexOf("|");
        while(pos != -1)
        {
            left = rangeStr.left(pos);
            int lpos = left.indexOf(",");

            if(left.contains("(") && left.contains(")"))
            {
                l_left = left.left(lpos).remove("(");
                l_right = left.remove(0, lpos+1).remove(")");

                if(l_left == "~" && l_right == "~")
                {
                    ret = true;
                }
                else if(l_left == "~" && l_right != "~")
                {
                    if(value < l_right.toDouble())
                    {
                        ret = true;
                    }
                }
                else if(l_left != "~" && l_right == "~")
                {
                    if(value > l_left.toDouble())
                    {
                        ret = true;
                    }
                }
                else
                {
                    if(value > l_left.toDouble() && value < l_right.toDouble())
                    {
                        ret = true;
                    }
                }
            }
            if(left.contains("[") && left.contains("]"))
            {
                l_left = left.left(lpos).remove("[");
                l_right = left.remove(0, lpos+1).remove("]");

                if(value >= l_left.toDouble() && value <= l_right.toDouble())
                {
                    ret = true;
                }
            }
            if(left.contains("(") && left.contains("]"))
            {
                l_left = left.left(lpos).remove("(");
                l_right = left.remove(0, lpos+1).remove("]");

                if(l_left == "~" && l_right != "~")
                {
                    if(value <= l_right.toDouble())
                    {
                        ret = true;
                    }
                }
                else if(l_left != "~" && l_right != "~")
                {
                    if(value > l_left.toDouble() && value <= l_right.toDouble())
                    {
                        ret = true;
                    }
                }
            }
            if(left.contains("[") && left.contains(")"))
            {
                l_left = left.left(lpos).remove("[");
                l_right = left.remove(0, lpos+1).remove(")");

                if(l_left != "~" && l_right == "~")
                {
                    if(value >= l_left.toDouble())
                    {
                        ret = true;
                    }
                }
                else if(l_left != "~" && l_right != "~")
                {
                    if(value >= l_left.toDouble() && value < l_right.toDouble())
                    {
                        ret = true;
                    }
                }
            }

            rangeStr.remove(0, pos+1);
            pos = rangeStr.indexOf("|");
        }
        if(rangeStr.contains("(")&&rangeStr.contains(")"))
        {
            pos = rangeStr.indexOf(",");
            l_left = rangeStr.left(pos).remove("(");
            l_right = rangeStr.remove(0,pos+1).remove(")");
            if(l_left == "~" && l_right == "~")
            {
                ret = true;
            }
            else if(l_left == "~" && l_right != "~")
            {
                if(value < l_right.toDouble())
                {
                    ret = true;
                }
            }
            else if(l_left != "~" && l_right == "~")
            {
                if(value > l_left.toDouble())
                {
                    ret = true;
                }
            }
            else
            {
                if(value > l_left.toDouble() && value < l_right.toDouble())
                {
                    ret = true;
                }
            }

        }
        if(rangeStr.contains("[")&&rangeStr.contains("]"))
        {
            int pos = rangeStr.indexOf(",");
            l_left = rangeStr.left(pos).remove("[");
            l_right = rangeStr.remove(0, pos+1).remove("]");
            if(value >= l_left.toDouble() && value <= l_right.toDouble())
            {
                ret = true;
            }
        }
        if(rangeStr.contains("(")&&rangeStr.contains("]"))
        {
            int pos = rangeStr.indexOf(",");
            l_left = rangeStr.left(pos).remove("(");
            l_right = rangeStr.remove(0, pos+1).remove("]");
            if(l_left == "~" && l_right != "~")
            {
                if(value <= l_right.toDouble())
                {
                    ret = true;
                }
            }
            else if(l_left != "~" && l_right != "~")
            {
                if(value > l_left.toDouble() && value <= l_right.toDouble())
                {
                    ret = true;
                }
            }
        }
        if(rangeStr.contains("[")&&rangeStr.contains(")"))
        {
            int pos = rangeStr.indexOf(",");
            l_left = rangeStr.left(pos).remove("[");
            l_right = rangeStr.remove(0, pos+1).remove(")");
            if(l_left != "~" && l_right == "~")
            {
                if(value >= l_left.toDouble())
                {
                    ret = true;
                }
            }
            else if(l_left != "~" && l_right != "~")
            {
                if(value >= l_left.toDouble() && value < l_right.toDouble())
                {
                    ret = true;
                }
            }
        }

    }
    return ret;
}

 

posted @ 2017-04-05 23:27  朱小勇  阅读(463)  评论(0编辑  收藏  举报