Qt 获取文本输入、设置快捷键、中文显示支持、字体设置、Mac输入框、正则表达式

不废话,直接上代码

//send.h

#ifndef SEND_H_
#define SEND_H_
#include <QDebug>
#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QTextCodec>
#include "MyMacAddrEdit.h"
#include "MyMacPartLineEdit.h"
using namespace std;

class MyMainWindows:public QWidget       //申明一个MyMainWindows类,这个类用于实现窗体
{
    Q_OBJECT                             //Q_OBJECT是在定制信号和槽和必须包含的一条宏语句
public:
    MyMainWindows();                     //类构造函数(用于实现程序的主体部份)
    ~MyMainWindows();
    /*void ::keyPressEvent(QKeyEvent  *event)
    {
        if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
        {
            //按钮槽函数
        }
    }*/
public slots:                            //所有的槽函数都必须申明public slots语句内
    void Json_send();                    //这个槽函数用于显应点击按钮时改变文本框内容
private:
    QPushButton * sendBtn;               //申请一个按钮QPushButton
    //QLineEdit * Mac;                     //申请一个文本框ledit
    QLineEdit * DeviceName;
    QLineEdit * Password;
    QLineEdit * DeviceID;
    QLineEdit * ServReturn;
    MymacAddrEdit *MacAddr;

    QLabel *labelMac;
    QLabel *labelDeviceName;
    QLabel *labelPassword;
    QLabel *labelDeviceID;
    QLabel *labelServReturn;

    QString JsonText;
};


#endif // SEND_H_

//send.cpp

#include "send.h"
#include "GetJson.h"
#include "tcpclient.h"
#include "mainwindow.h"
#include "MyMacAddrEdit.h"
#include "MyMacPartLineEdit.h"
#include <QRegExpValidator>
#include <QLabel>
#include <QPalette>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//MyMainWindows的构造函数
MyMainWindows::MyMainWindows()                                     //实现构造函数
{
    setGeometry(770, 200, 660, 480);                               //绘制主窗体,大小为640, 480
    setAutoFillBackground(true);
    QPalette palette;
    palette.setColor(QPalette::Background, QColor(74,78,76));
    //palette.setBrush(QPalette::Background, QBrush(QPixmap(":/image/background.png")));
    setPalette(palette);
    //设置中文显示支持
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("gb2312"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("gb2312"));
    QTextCodec::setCodecForTr( QTextCodec::codecForName("gb2312"));
    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());        //设置QObject::tr()函数所要使用的字符集
    //sendBtn
    sendBtn = new QPushButton("Write",this);                        //实现sendBtn按钮,被设计其名字为 “烧写”
    sendBtn->setFont(QFont("Times", 14, QFont::Bold));              //字体设置
    sendBtn->setGeometry(140, 360, 60, 30);                         //按钮大小位置设定
    sendBtn->setShortcut(QKeySequence::InsertParagraphSeparator);   //设置快捷键为键盘的“回车”键

    //烧写信息框初始化
    //Mac
    MacAddr = new MymacAddrEdit(this);
    /*QRegExp regExp("^([0-9A-F]{2})(-[0-9A-F]{2}){5}$"); //Mac地址正则表达式
    QRegExpValidator *pRevalidotor = newQRegExpValidator(regExp, this);
    MacAddr->setValidator(new QRegExpValidator(regExp, this));*/
    labelMac = new QLabel(tr("Mac"),this,0);
    labelMac->setGeometry(20,30,120,40);  ;
    labelMac->setFont(QFont("Times", 16, QFont::Black));
    //DeviceName
    DeviceName = new QLineEdit(0,this);                             //实现text文件框
    //DeviceName->setPlaceholderText(" please input DeviceName");
    DeviceName->setObjectName("DeviceName");
    DeviceName->setGeometry(160,90,480,40);                         //绘制text文件框位置和大小
    DeviceName->setFont(QFont("Times", 16, QFont::Black));
    labelDeviceName = new QLabel(tr("DeviceName"),this,0);
    labelDeviceName->setGeometry(20,90,120,40);  ;
    labelDeviceName->setFont(QFont("Times", 16, QFont::Black));
    //Password
    Password = new QLineEdit(0,this);                               //实现text文件框
    //Password->setPlaceholderText("please inputPassword");
    Password->setObjectName("Password");
    Password->setGeometry(160,150,480,40);                          //绘制text文件框位置和大小
    Password->setFont(QFont("Times", 16, QFont::Black));
    labelPassword = new QLabel(tr("Password"),this,0);
    labelPassword->setGeometry(20,150,120,40);  ;
    labelPassword->setFont(QFont("Times", 16, QFont::Black));
    //DeviceID
    DeviceID = new QLineEdit(0,this);                               //实现text文件框
    //DeviceID->setPlaceholderText("please input DeviceID");
    DeviceID->setObjectName("DeviceID");
    DeviceID->setGeometry(160,210,480,40);                          //绘制text文件框位置和大小
    DeviceID->setFont(QFont("Times", 16, QFont::Black));
    labelDeviceID = new QLabel(tr("DeviceID"),this,0);
    labelDeviceID->setGeometry(20,210,120,40);  ;
    labelDeviceID->setFont(QFont("Times", 16, QFont::Black));
    //ServReturn
    ServReturn = new QLineEdit(0,this);                             //实现text文件框
    ServReturn->setPlaceholderText("You can get the return value from here");
    ServReturn->setObjectName("ServReturn");
    ServReturn->setGeometry(160,270,480,40);                        //绘制text文件框位置和大小
    ServReturn->setFont(QFont("Times", 16, QFont::Black));
    labelServReturn = new QLabel(tr("ServReturn"),this,0);
    labelServReturn->setGeometry(20,270,120,40);
    labelServReturn->setFont(QFont("Times", 16, QFont::Black));

    connect( sendBtn, SIGNAL(clicked() ),this, SLOT( Json_send() ) );  //连接sendBtn按钮的点击clicked()信号和自定义槽SlotTest()
}
//MyMainWindows的析构函数
MyMainWindows::~MyMainWindows()
{
    if( NULL != sendBtn) delete sendBtn;
    //if( NULL != Mac) delete Mac;
    if( NULL != DeviceName) delete DeviceName;
    if( NULL != Password) delete Password;
    if( NULL != DeviceID) delete DeviceID;
    if( NULL != labelMac) delete labelMac;
    if( NULL != labelDeviceName) delete labelDeviceName;
    if( NULL != labelPassword) delete labelPassword;
    if( NULL != labelDeviceID) delete labelDeviceID;
    if( NULL != labelServReturn) delete labelServReturn;
}

void MyMainWindows::Json_send()                                         //自定义槽函数的实现方法,点击按钮发送数据给服务器
{
    static bool num = 0;
    int iResult;
    char temp[100];
    char *buf[2] = {
        (char*)"{\"method\":\"LOGIN\", \"params\":{\"PWD\":\"admin\"}, \"id\":\"122323\"}",     //LogInfo
        (char*)"{\"method\":\"RESTART\", \"params\":\"NULL\", \"id\":\"\" }"                    //reboot
    };

    create_objects();                                                   //create Json package
    if(TestFork(this)){
        QMessageBox::information(this,"Information","connect server failed");
        closesocket(ConnectSocket);
        WSACleanup();
        return;
    }
    //User log
    if( 0 == num ){
        iResult = send( ConnectSocket, buf[0], strlen( buf[0] ), 0);
        if ( iResult == SOCKET_ERROR ) {
            QMessageBox::information( this, "Information","send failed" );
            closesocket( ConnectSocket );
            WSACleanup();
            return;
        }
        iResult = recv( ConnectSocket, temp, 100, 0);                   //接收
        if ( iResult == 0 )
            QMessageBox::information( this, "Information", "Connection closed" );
        else if( iResult < 0 )
            QMessageBox::information( this, "Information", "recv failed" );
    }
    num = 1;
    //package data
    JsonText.append( "{\"method\":\"MODIFY_HARDINFO\", \"params\":{\"MAC_START\":\"" );
    JsonText.append( MacAddr->text() );
    JsonText.append( "\", \"DEVNAME\":\"" );
    JsonText.append( DeviceName->text() );
    JsonText.append( "\", \"DEVPSW\":\"" );
    JsonText.append( Password->text() );
    JsonText.append( "\", \"DEVID\":\"" );
    JsonText.append( DeviceID->text() );
    JsonText.append( "\"}, \"id\":\"823456\"}" );
    qDebug()<<"debug:"<<JsonText.toLatin1().data();
    iResult = send( ConnectSocket, JsonText.toLatin1().data(), JsonText.length(), 0 );//JsonText.toLatin1().data()即JsonText的char* 格式  // 发送信息
    if ( iResult == SOCKET_ERROR ) {
        QMessageBox::information( this, "Information", "send failed" );
        closesocket( ConnectSocket );
        WSACleanup();
        return;
    }
    memset( temp,0,sizeof( temp ) );
    Sleep(1300);
    iResult = recv( ConnectSocket, temp, sizeof( temp ), 0 );              //接收
    if ( iResult == 0 )
        QMessageBox::information( this, "Information", "Connection closed" );
    else if( iResult < 0 )
        QMessageBox::information(this, "Information", "recv failed");

    //判断返回信息
    //qDebug()<<"debug:"<<temp;
    char * result = temp;
    result = strtok(result, "\"");
    result = strtok(NULL, "\"");
    if(NULL == result){
        ServReturn->setText( "NULL" );
        QMessageBox::information(this, "Information", "Try Again!");
        return;
    }
    //qDebug()<<"debug:"<<result;
    if(0 == strcmp(result,"error"))
        ServReturn->setText( "ERROR" );
    else if(0 == strcmp(result,"result"))
    {
        num = 0;
        ServReturn->setText( "OK  Restarting" );
        iResult = send( ConnectSocket, buf[1], strlen( buf[1] ), 0);
        if ( iResult == SOCKET_ERROR ) {
            QMessageBox::information( this, "Information","send failed" );
            closesocket( ConnectSocket );
            WSACleanup();
            return;
        }
    }
    else
        ServReturn->setText( "ERROR" );
    JsonText.clear();                                                    //清除上次内容
    if ( SOCKET_ERROR == closesocket(ConnectSocket) ) {
        QMessageBox::information( this, "Information","close socket fialed" );
        WSACleanup();
        return;
    }
    WSACleanup();
    return;
}

//MyMacAddrEdit.h

#ifndef MYMACADDREDIT_H
#define MYMACADDREDIT_H
#include <QWidget>
#include <QRegExpValidator>
class QLineEdit;
class QLabel;
class MymacPartLineEdit;

class MymacAddrEdit : public QWidget
{
    Q_OBJECT
public:
    MymacAddrEdit(QWidget* pParent = 0);
    ~MymacAddrEdit();
    void MacJudgement(const QString &text);
    void settext(const QString &text);
    QString text();
    void setStyleSheet(const QString &styleSheet);


signals:
    //void textchanged(const QString& text);
    //void textedited(const QString &text);

private slots:
    //void textchangedslot(const QString& text);
    //void texteditedslot(const QString &text);
public:
    QRegExpValidator *pReg;
    MymacPartLineEdit *MacPart1_;
    MymacPartLineEdit *MacPart2_;
    MymacPartLineEdit *MacPart3_;
    MymacPartLineEdit *MacPart4_;
    MymacPartLineEdit *MacPart5_;
    QLineEdit *MacPart6_;

    QLabel *labeldot1_;
    QLabel *labeldot2_;
    QLabel *labeldot3_;
    QLabel *labeldot4_;
    QLabel *labeldot5_;

};
#endif // MYMACADDREDIT_H
//MyMacAddrEdit.cpp

#include "MyMacAddrEdit.h"
#include <QRegExpValidator>
#include <QLabel>
#include "MyMacPartLineEdit.h"
#include "send.h"
MymacAddrEdit::MymacAddrEdit(QWidget* pParent /* = 0 */)
: QWidget(pParent)
{
    //setGeometry(160,30,480,40);
    QRegExp regexp;                     //Mac地址正则表达式 用于输入范围限制
    regexp.setPattern(QString("^([0-9a-f]{2})(-[0-9A-F]{2}){5}$"));
    pReg = new QRegExpValidator(regexp, this);

    setFont(QFont("Times", 16, QFont::Black));
    MacPart1_ = new MymacPartLineEdit(0,this);
    MacPart1_->setValidator(pReg);      //MacPart1_ 输入范围限制
    MacPart1_->setText("dc");
    MacPart2_ = new MymacPartLineEdit(0,this);
    MacPart2_->setValidator(pReg);
    MacPart2_->setText("a3");
    MacPart3_ = new MymacPartLineEdit(0,this);
    MacPart3_->setValidator(pReg);
    MacPart3_->setText("ac");
    MacPart4_ = new MymacPartLineEdit(0,this);
    MacPart4_->setValidator(pReg);
    MacPart4_->setFocus();
    MacPart5_ = new MymacPartLineEdit(0,this);
    MacPart5_->setValidator(pReg);
    MacPart6_ = new MymacPartLineEdit(0,this);
    MacPart6_->setValidator(pReg);


    labeldot1_ = new QLabel(this);
    labeldot2_ = new QLabel(this);
    labeldot3_ = new QLabel(this);
    labeldot4_ = new QLabel(this);
    labeldot5_ = new QLabel(this);

    MacPart1_->setGeometry(QRect(160, 30, 80, 40));
    MacPart2_->setGeometry(QRect(240, 30, 80, 40));
    MacPart3_->setGeometry(QRect(320, 30, 80, 40));
    MacPart4_->setGeometry(QRect(400, 30, 80, 40));
    MacPart5_->setGeometry(QRect(480, 30, 80, 40));
    MacPart6_->setGeometry(QRect(560, 30, 80, 40));

    labeldot1_->setFont(QFont("Times", 16, QFont::Black));
    labeldot1_->setText(" :");
    labeldot1_->setGeometry(QRect(238, 30, 12, 40));
    labeldot1_->setAlignment(Qt::AlignCenter);

    labeldot2_->setFont(QFont("Times", 16, QFont::Black));
    labeldot2_->setText(" :");
    labeldot2_->setGeometry(QRect(318, 30, 12, 40));
    labeldot2_->setAlignment(Qt::AlignCenter);

    labeldot3_->setText(" :");
    labeldot3_->setGeometry(QRect(398, 30, 12, 40));
    labeldot3_->setAlignment(Qt::AlignCenter);

    labeldot4_->setText(" :");
    labeldot4_->setGeometry(QRect(478, 30, 12, 40));
    labeldot4_->setAlignment(Qt::AlignCenter);

    labeldot5_->setText(" :");
    labeldot5_->setGeometry(QRect(558, 30, 12, 40));
    labeldot5_->setAlignment(Qt::AlignCenter);

    QWidget::setTabOrder(MacPart1_, MacPart2_);
    QWidget::setTabOrder(MacPart2_, MacPart3_);
    QWidget::setTabOrder(MacPart3_, MacPart4_);
    QWidget::setTabOrder(MacPart4_, MacPart5_);
    QWidget::setTabOrder(MacPart5_, MacPart6_);
    MacPart1_->set_nexttab_edit(MacPart2_);
    MacPart2_->set_nexttab_edit(MacPart3_);
    MacPart3_->set_nexttab_edit(MacPart4_);
    MacPart4_->set_nexttab_edit(MacPart5_);
    MacPart5_->set_nexttab_edit(MacPart6_);

    /*connect(MacPart1_, SIGNAL(textChanged(const QString&)), this, SLOT(textchangedslot(const QString&)));
    connect(MacPart2_, SIGNAL(textChanged(const QString&)), this, SLOT(textchangedslot(const QString&)));
    connect(MacPart3_, SIGNAL(textChanged(const QString&)), this, SLOT(textchangedslot(const QString&)));
    connect(MacPart4_, SIGNAL(textChanged(const QString&)), this, SLOT(textchangedslot(const QString&)));
    connect(MacPart5_, SIGNAL(textChanged(const QString&)), this, SLOT(textchangedslot(const QString&)));
    connect(MacPart6_, SIGNAL(textChanged(const QString&)), this, SLOT(textchangedslot(const QString&)));

    connect(MacPart1_, SIGNAL(textEdited (const QString&)), this, SLOT(texteditedslot(const QString&)));
    connect(MacPart2_, SIGNAL(textEdited (const QString&)), this, SLOT(texteditedslot(const QString&)));
    connect(MacPart3_, SIGNAL(textEdited (const QString&)), this, SLOT(texteditedslot(const QString&)));
    connect(MacPart4_, SIGNAL(textEdited (const QString&)), this, SLOT(texteditedslot(const QString&)));
    connect(MacPart5_, SIGNAL(textEdited (const QString&)), this, SLOT(texteditedslot(const QString&)));
    connect(MacPart6_, SIGNAL(textEdited (const QString&)), this, SLOT(texteditedslot(const QString&)));
    */
}

MymacAddrEdit::~MymacAddrEdit()
{
    if( NULL != pReg) delete pReg;
    if( NULL != MacPart1_) delete MacPart1_;
    if( NULL != MacPart2_) delete MacPart2_;
    if( NULL != MacPart3_) delete MacPart3_;
    if( NULL != MacPart4_) delete MacPart4_;
    if( NULL != MacPart5_) delete MacPart5_;
    if( NULL != MacPart6_) delete MacPart6_;
    if( NULL != labeldot1_) delete labeldot1_;
    if( NULL != labeldot2_) delete labeldot2_;
    if( NULL != labeldot3_) delete labeldot3_;
    if( NULL != labeldot4_) delete labeldot4_;
    if( NULL != labeldot5_) delete labeldot5_;
}

/*void MymacAddrEdit::textchangedslot(const QString&)*/
/*{
    QString MacPart1, MacPart2, MacPart3, MacPart4, MacPart5, MacPart6;
    MacPart1 = MacPart1_->text();
    MacPart2 = MacPart2_->text();
    MacPart3 = MacPart3_->text();
    MacPart4 = MacPart4_->text();
    MacPart5 = MacPart5_->text();
    MacPart6 = MacPart6_->text();

    QString ipaddr = QString("%1:%2:%3:%4:%5:%6")
                     .arg(MacPart1)
                     .arg(MacPart2)
                     .arg(MacPart3)
                     .arg(MacPart4)
                     .arg(MacPart5)
                     .arg(MacPart6);

    emit textchanged(ipaddr);
}*/

/*void MymacAddrEdit::texteditedslot(const QString &)
{
    QString MacPart1, MacPart2, MacPart3, MacPart4, MacPart5, MacPart6;
    MacPart1 = MacPart1_->text();
    MacPart2 = MacPart2_->text();
    MacPart3 = MacPart3_->text();
    MacPart4 = MacPart4_->text();
    MacPart5 = MacPart5_->text();
    MacPart6 = MacPart6_->text();

    QString ipaddr = QString("%1:%2:%3:%4:%5:%6")
        .arg(MacPart1)
        .arg(MacPart2)
        .arg(MacPart3)
        .arg(MacPart4)
        .arg(MacPart5)
        .arg(MacPart6);

    emit textedited(ipaddr);
}*/

void MymacAddrEdit::settext(const QString &text)
{
    /*QString MacPart1, MacPart2, MacPart3, MacPart4, MacPart5, MacPart6;
    QString qstring_validate = text;

    // Mac地址验证
    QRegExp regexp("^([0-9a-f]{2})(-[0-9A-F]{2}){5}$"); //Mac地址正则表达式
    QRegExpValidator regexp_validator(regexp, this);
    int nPos = 0;
    QValidator::State state = regexp_validator.validate(qstring_validate, nPos);
    // IP合法
    if (state == QValidator::Acceptable)
    {
        QStringList MacPartlist = text.split(":");

        int strcount = MacPartlist.size();
        int index = 0;
        if (index < strcount)
        {
            MacPart1 = MacPartlist.at(index);
        }
        if (++index < strcount)
        {
            MacPart2 = MacPartlist.at(index);
        }
        if (++index < strcount)
        {
            MacPart3 = MacPartlist.at(index);
        }
        if (++index < strcount)
        {
            MacPart4 = MacPartlist.at(index);
        }
        if (++index < strcount)
        {
            MacPart5 = MacPartlist.at(index);
        }
        if (++index < strcount)
        {
            MacPart6 = MacPartlist.at(index);
        }
    }

    MacPart1_->setText(MacPart1);
    MacPart2_->setText(MacPart2);
    MacPart3_->setText(MacPart3);
    MacPart4_->setText(MacPart4);
    MacPart5_->setText(MacPart5);
    MacPart6_->setText(MacPart6);*/
}

void MymacAddrEdit::MacJudgement(const QString &text)
{
    /*// Mac地址验证
    int nPos = 0;
    QString qstring_validate = text;
    QRegExp regexp; //Mac地址正则表达式
    regexp.setPattern(QString("^([0-9a-f]{2})(-[0-9A-F]{2}){5}$"));
    QRegExpValidator regexp_validator(regexp, this);
    MacPart4_->setValidator(new QRegExpValidator(regexp, this));
    QValidator::State state = regexp_validator.validate(qstring_validate,nPos);
    // Mac合法
    if (state == QValidator::Acceptable)
        qDebug()<<"debug:"<<"ok";
    else
        qDebug()<<"debug:"<<"MacError";*/
}

QString MymacAddrEdit::text()
{
    QString MacPart1, MacPart2, MacPart3, MacPart4, MacPart5, MacPart6;
    MacPart1 = MacPart1_->text();
    MacPart2 = MacPart2_->text();
    MacPart3 = MacPart3_->text();
    MacPart4 = MacPart4_->text();
    MacPart5 = MacPart5_->text();
    MacPart6 = MacPart6_->text();

    return QString("%1:%2:%3:%4:%5:%6")
        .arg(MacPart1)
        .arg(MacPart2)
        .arg(MacPart3)
        .arg(MacPart4)
        .arg(MacPart5)
        .arg(MacPart6);
}

void MymacAddrEdit::setStyleSheet(const QString &styleSheet)
{
    MacPart1_->setStyleSheet(styleSheet);
    MacPart2_->setStyleSheet(styleSheet);
    MacPart3_->setStyleSheet(styleSheet);
    MacPart4_->setStyleSheet(styleSheet);
    MacPart5_->setStyleSheet(styleSheet);
    MacPart6_->setStyleSheet(styleSheet);
}

//MyMacPartEdit.h

#ifndef MYMACADDRLINEEDIT_H
#define MYMACADDRLINEEDIT_H
#include <QLineEdit>

class QWidget;
class QFocusEvent;
class QKeyEvent;

class MymacPartLineEdit : public QLineEdit
{
    Q_OBJECT
public:
    MymacPartLineEdit( const QString &Text, QWidget *parent = 0);
    ~MymacPartLineEdit(void);

    void set_nexttab_edit(QLineEdit *nexttab) { next_tab_ = nexttab; }

protected:
    virtual void focusInEvent(QFocusEvent *e);
    virtual    void keyPressEvent(QKeyEvent *event);

private slots:
    void text_edited(const QString& text);

private:
    QLineEdit *next_tab_;
};
#endif // MYIPPARTLINEEDIT_H

//MyMacPartEdit.cpp

#include "MyMacPartLineEdit.h"
#include <QIntValidator>
#include <QKeyEvent>
#include "send.h"
MymacPartLineEdit::MymacPartLineEdit(const QString &Text, QWidget *parent/* = 0*/)
: QLineEdit(parent)
{
    next_tab_ = NULL;
    this->setMaxLength(2);
    this->setFrame(false);
    this->setAlignment(Qt::AlignCenter);

    //QValidator *validator = new QIntValidator(0, 255, this);
    //this->setValidator(validator);

    connect(this, SIGNAL(textEdited(const QString&)), this, SLOT(text_edited(const QString&)));
}

MymacPartLineEdit::~MymacPartLineEdit(void)
{
}

void MymacPartLineEdit::focusInEvent(QFocusEvent *e)
{
    this->selectAll();
    QLineEdit::focusInEvent(e);
}

void MymacPartLineEdit::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Period)
    {
        if (next_tab_)
        {
            next_tab_->setFocus();
            next_tab_->selectAll();
        }
    }
    QLineEdit::keyPressEvent(event);
}

void MymacPartLineEdit::text_edited(const QString& text)
{
    QIntValidator v(0, 9, this);
    QString macaddr = text;
    //int pos = 0;
    //QValidator::State state = v.validate(macaddr, pos);
    if (1 /*state == QValidator::Acceptable*/)
    {
        if (macaddr.size() > 1)
        {
            if (macaddr.size() == 2)
            {
                //int ipnum = macaddr.toInt();

                if (1/*ipnum > 25*/)
                {
                    if (next_tab_)
                    {
                        next_tab_->setFocus();    //自动退格
                        next_tab_->selectAll();
                    }
                }
            }
            else
            {
                if (next_tab_)
                {
                    next_tab_->setFocus();          //自动退格
                    next_tab_->selectAll();
                }
            }
        }
    }
}


//TcpClient.h

#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <cstdio>
#include "send.h"


extern SOCKET ConnectSocket;
int TestFork(MyMainWindows *w);

#endif // TCPCLIENT_H

//TcpClient.cpp

//client : 8010端口   IP:192.168.5.1
#include "GetJson.h"
#include "tcpclient.h"
#include "send.h"

using namespace std;

// Need to link with Ws2_32.lib
//#pragma comment(lib, "ws2_32.lib")
SOCKET ConnectSocket;
int TestFork(MyMainWindows *w)
{
    //----------------------
    // Initialize Winsock
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        //QMessageBox::information(w,"Information","WSAStartup function failed"); //error
        return 1;
    }
    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        QMessageBox::information(w,"Information","socket function failed");
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("192.168.5.1");
    clientService.sin_port = htons(8010);

    /*int iRecvTimeOut = 3000;
    iResult = setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&iRecvTimeOut, sizeof(int));
    if( SOCKET_ERROR  == iResult)
    {
        //qDebug()<<"debug:"<<"setsockopt";
    }8*/
    //设置非阻塞方式连接
    //unsigned long ul = 1;
    //iResult = ioctlsocket(ConnectSocket, FIONBIO, (unsigned long*)&ul);
    //if( SOCKET_ERROR  == iResult)
    //{
    //    qDebug()<<"debug:"<<"ioctlsocket";
    //}
    //----------------------
    // Connect to server.
    iResult = connect(ConnectSocket, (SOCKADDR *) &clientService, sizeof(clientService) );
    if (iResult == SOCKET_ERROR) {
        //QMessageBox::information(w,"Information","Connect Fialed!!!!!!");
        return 1;
    }
    //连接超时3秒
    /*struct timeval timeout ;
    fd_set r;
    FD_ZERO(&r);
    FD_SET(ConnectSocket, &r);
    timeout.tv_sec = 3; //连接超时3秒
    timeout.tv_usec =0;
    iResult = select(0, 0, &r, 0, &timeout);
    if ( iResult <= 0 )
    {
        closesocket(ConnectSocket);
        //QMessageBox::information(w,"Information","Connect Timeout!");
        return 1;
    }*/
    return 0;
}

 

posted on 2015-04-27 15:58  风海蓝天  阅读(1480)  评论(0)    收藏  举报

导航