QLineEdit 实现ip输入

工程目录如下

QLineEdit 实现ip输入_第1张图片

创建一个 基于QWidget 的空白工程,添加 C++ class ,也就是 iplineedit.cpp 和 iplienedit.h 这两个文件, 新添加的用于继承 QLineEdit 类重新写一个用于ip输入的类

iplineedit.cpp 文件内容: 

#include "iplineedit.h"
#include 
#include 
#include 
#include 
#include 
#include 

IPLineEdit::IPLineEdit(QWidget *parent)
    : QLineEdit(parent)
{
    QRegExp rx("(2[0-5]{2}|2[0-4][0-9]|1?[0-9]{1,2})");
    QHBoxLayout *pHBox = new QHBoxLayout(this);
    pHBox->setSpacing(10);
    pHBox->setContentsMargins(0, 0, 0, 0);
    for (int i = 0; i < 4; i++)
    {
        m_lineEidt[i] = new QLineEdit(this);
        m_lineEidt[i]->setStyleSheet("background:rgb(222,122,112);");  // 输入框背景 QColor(222,122,112)
        m_lineEidt[i]->setFrame(false);
        m_lineEidt[i]->setMaxLength(3);
        m_lineEidt[i]->setAlignment(Qt::AlignCenter);
        m_lineEidt[i]->installEventFilter(this);
        m_lineEidt[i]->setValidator(new QRegExpValidator(rx, this));
        m_lineEidt[i]->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        pHBox->addWidget(m_lineEidt[i]);
    }
    this->setReadOnly(true);
}

IPLineEdit::~IPLineEdit()
{

}

void IPLineEdit::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);
    QPainter painter(this);
    QBrush brush;
    brush.setStyle(Qt::BrushStyle::SolidPattern);
    QPen pen;


    int width = 0;
    for (int i = 0; i < 3; i++)
    {
        width += m_lineEidt[i]->width() + (i == 0 ? 3 : 10);//布局的间隔

        // 画矩形,画为与输入栏相同颜色
        brush.setColor(QColor(222,122,112));  // 设置画刷颜色
        painter.setBrush(brush);

        pen.setColor(QColor(222,122,112));    // 设置画笔颜色
        painter.setPen(pen);
        painter.drawRect(width-4, 0, 10, height());


        // 画IP 点分
        brush.setColor(Qt::black);    // 设置画刷颜色
        painter.setBrush(brush);

        pen.setColor(QColor(0,0,0));  // 设置画笔颜色
        painter.setPen(pen);
        painter.drawEllipse(width, height()/2-2, 4, 4);  // 点分
    }
}

int IPLineEdit::getIndex(QLineEdit *pEdit)
{
    int index = -1;
    for (int i = 0; i < 4; i++)
    {
        if (pEdit == m_lineEidt[i])
            index = i;
    }
    return index;
}

bool IPLineEdit::eventFilter(QObject *obj, QEvent *ev)
{
    if (children().contains(obj) && QEvent::KeyPress == ev->type())
    {
        QKeyEvent *keyEvent = dynamic_cast(ev);
        QLineEdit *pEdit = qobject_cast(obj);
        switch (keyEvent->key())
        {
        case Qt::Key_0:
        case Qt::Key_1:
        case Qt::Key_2:
        case Qt::Key_3:
        case Qt::Key_4:
        case Qt::Key_5:
        case Qt::Key_6:
        case Qt::Key_7:
        case Qt::Key_8:
        case Qt::Key_9:
        {
            QString strText = pEdit->text();
            if (pEdit->selectedText().length())
            {
                pEdit->text().replace(pEdit->selectedText(), QChar(keyEvent->key()));
            }
            else if (strText.length() == 3 || strText.length() < 3 && strText.toInt() * 10 > 255)
            {
                int index = getIndex(pEdit);
                if (index != -1 && index != 3)
                {
                    m_lineEidt[index + 1]->setFocus();
                    m_lineEidt[index + 1]->selectAll();
                }
            }
            else if (strText.length() == 2 && strText.toInt() * 10 < 255)
            {
                if (Qt::Key_0 == keyEvent->key() && strText.toInt())
                {
                    pEdit->setText(strText.insert(pEdit->cursorPosition(), QChar(Qt::Key_0)));
                }
            }
            return QWidget::eventFilter(obj, ev);
        }
        break;
        case Qt::Key_Backspace:
        {
            QString strText = pEdit->text();
            if (!strText.length() || strText.length() && !pEdit->cursorPosition())
            {
                int index = getIndex(pEdit);
                if (index != -1 && index != 0)
                {
                    m_lineEidt[index - 1]->setFocus();
                    int length = m_lineEidt[index - 1]->text().length();
                    m_lineEidt[index - 1]->setCursorPosition(length ? length : 0);
                }
            }
            return QWidget::eventFilter(obj, ev);
        }
        case Qt::Key_Left:
        {
            if (!pEdit->cursorPosition())
            {
                int index = getIndex(pEdit);
                if (index != -1 && index != 0)
                {
                    m_lineEidt[index - 1]->setFocus();
                    int length = m_lineEidt[index - 1]->text().length();
                    m_lineEidt[index - 1]->setCursorPosition(length ? length : 0);
                }
            }
            return QWidget::eventFilter(obj, ev);
        }
        case Qt::Key_Right:
        {
            if (pEdit->cursorPosition() == pEdit->text().length())
            {
                int index = getIndex(pEdit);
                if (index != -1 && index != 3)
                {
                    m_lineEidt[index + 1]->setFocus();
                    m_lineEidt[index + 1]->setCursorPosition(0);
                }
            }
            return QWidget::eventFilter(obj, ev);
        }
        default:
            break;
        }
    }
    return false;
}

void IPLineEdit::setText(const QString &strIP)
{
    if (!isTextValid(strIP))
    {
        QMessageBox::warning(this, "Attention", "Your IP Address is Invalid!", QMessageBox::StandardButton::Ok);
        return;
    }
    else
    {
        int i = 0;
        QStringList ipList = strIP.split(".");
        foreach(QString ip , ipList)
        {
            m_lineEidt[i]->setText(ip);
            i++;
        }
    }
}

bool IPLineEdit::isTextValid(const QString &strIP)
{
    QRegExp rx2("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
    if (!rx2.exactMatch(strIP))
        return false;
    return true;
}

QString IPLineEdit::text() const
{
    QString strIP;
    for (int i = 0; i < 4; i++)
    {
        strIP.append(m_lineEidt[i]->text());
        if(i<3)
        {
            strIP.append(".");
        }
    }
    return strIP;
}
iplineedit.h 文件:
#ifndef IPLINEEDIT_H
#define IPLINEEDIT_H

#include 
#include 
#include 

class IPLineEdit : public QLineEdit
{
    Q_OBJECT

public:
    IPLineEdit(QWidget *parent = 0);
    ~IPLineEdit();

    void setText(const QString &strIP);
    QString text() const;
//    void setStyleSheet(const QString& styleSheet);
protected:
    void paintEvent(QPaintEvent *event);
    bool eventFilter(QObject *obj, QEvent *ev);

    int getIndex(QLineEdit *pEdit);
    bool isTextValid(const QString &strIP);
private:
    QLineEdit *m_lineEidt[4];
    QString mainBackground = ""; // 设置背景颜色,使4个输入框连成一个输入框
};


#endif // IPLINEEDIT_H

widget.cpp文件 :

#include "widget.h"
#include "ui_widget.h"
#include "iplineedit.h"

#include 
#include 

Widget::Widget(QWidget *parent) :QWidget(parent)
{   // 调用 自定义的类创建对象
    IPLineEdit *ip = new IPLineEdit(this);
    ip->move(100,100);
    ip->resize(200,50);
    ip->show();
    // 使用定时 2 秒打印一次ip输入框的内容
    QTimer *timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,
                [=]()
                {
                    qDebug()<<"ip:"<text();
                }
           );
    timer->start(2000);
}

Widget::~Widget()
{

}

其余都是创建工程时的原先文件未动

效果QLineEdit 实现ip输入_第2张图片

 

 

 

你可能感兴趣的:(Qt学习)