Qt版IP地址控件

头文件

#ifndef IPADDRESS_H
#define IPADDRESS_H

#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QHBoxLayout>

class ipAddress : public QWidget
{
    Q_OBJECT
public:
    explicit ipAddress(QWidget *parent = 0);

    bool validCheck();
    bool subCheck(QLineEdit*);
    QString getIPAddress();
    void textClear();

signals:

public slots:

public:

    QLabel *label1;
    QLabel *label2;
    QLabel *label3;

    QHBoxLayout *mainLayout;

    QLineEdit *number1;
    QLineEdit *number2;
    QLineEdit *number3;
    QLineEdit *number4;
};

#endif // IPADDRESS_H

源文件

#include "ipaddress.h"

ipAddress::ipAddress(QWidget *parent) :
    QWidget(parent)
{
//    布局
    mainLayout=new QHBoxLayout(this);
    label1=new QLabel(".",this);
    label2=new QLabel(".",this);
    label3=new QLabel(".",this);

    number1=new QLineEdit(this);
    number2=new QLineEdit(this);
    number3=new QLineEdit(this);
    number4=new QLineEdit(this);

    mainLayout->addWidget(number1);
    mainLayout->addWidget(label1);
    mainLayout->addWidget(number2);
    mainLayout->addWidget(label2);
    mainLayout->addWidget(number3);
    mainLayout->addWidget(label3);
    mainLayout->addWidget(number4);

    setLayout(mainLayout);

}

bool ipAddress::validCheck()
{//判断IP地址是否合理 
    return subCheck(number1) && subCheck(number2) && subCheck(number3) && subCheck(number4);
}

bool ipAddress::subCheck(QLineEdit *number)
{
    QString str=number->text();
    bool ok=true;
    int tmp=str.toInt(&ok,10);//合理性判断
    if(!ok)
        return false;

    if(tmp<0 || tmp>255)
        return false;
    return true;
}

QString ipAddress::getIPAddress()//get the IP address
{
    QString str;

    str+=number1->text();
    str+=".";
    str+=number2->text();
    str+=".";
    str+=number3->text();
    str+=".";
    str+=number4->text();

    return str;
}

void ipAddress::textClear()
{
    number1->clear();
    number2->clear();
    number3->clear();
    number4->clear();
}


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页