1 #include "qipaddressedititem.h" 2 #include <QtGui> 3 #include <QIntValidator> 4 #include <QMessageBox> QIpAddressEditItem(QWidget * parent)5QIpAddressEditItem::QIpAddressEditItem(QWidget *parent) : 6 QLineEdit(parent) 7 { 8 previousItem = NULL; 9 nextItem = NULL; 10 this->setMaxLength(3); 11 this->setFrame(false); 12 this->setAlignment(Qt::AlignCenter); 13 14 QIntValidator *validator = new QIntValidator(this); 15 validator->setBottom(0); 16 this->setValidator(validator); 17 18 connect(this, SIGNAL(textEdited(const QString &)), 19 this, SLOT(itemEdited(const QString &))); 20 } 21 focusInEvent(QFocusEvent * e)22void QIpAddressEditItem::focusInEvent(QFocusEvent *e) 23 { 24 this->selectAll(); 25 QLineEdit::focusInEvent(e); 26 } 27 keyPressEvent(QKeyEvent * event)28void QIpAddressEditItem::keyPressEvent(QKeyEvent *event) 29 { 30 if(event->key() == Qt::Key_Period) 31 { 32 if(nextItem != NULL) 33 { 34 nextItem->setFocus(); 35 nextItem->selectAll(); 36 } 37 } 38 if(event->key() == Qt::Key_Backspace) 39 { 40 QString text = this->text(); 41 if(text.isEmpty() && previousItem != NULL) 42 { 43 previousItem->setFocus(); 44 previousItem->setCursorPosition(previousItem->cursorPosition()); 45 previousItem->backspace(); 46 } 47 } 48 if(event->key() == Qt::Key_Left) 49 { 50 if(this->cursorPosition() == 0 && previousItem != NULL) 51 { 52 previousItem->setFocus(); 53 previousItem->setCursorPosition(previousItem->cursorPosition()); 54 } 55 } 56 if(event->key() == Qt::Key_Right) 57 { 58 int pos = this->cursorPosition(); 59 int length = this->text().length(); 60 if(pos == length && nextItem != NULL) 61 { 62 nextItem->setFocus(); 63 nextItem->setCursorPosition(0); 64 } 65 } 66 QLineEdit::keyPressEvent(event); 67 } 68 itemEdited(const QString & text)69void QIpAddressEditItem::itemEdited(const QString &text) 70 { 71 int num = text.toInt(); 72 if(num > 255 || num < 0) 73 { 74 QString message = text + " is not acceptable value.\n" + 75 "Please input the value bewteen 0 with 255."; 76 QMessageBox::warning(this, 77 tr("Warning"), 78 message); 79 this->setText("255"); 80 } 81 else if(text.length() == 3) 82 { 83 if(nextItem != NULL) 84 { 85 nextItem->setFocus(); 86 nextItem->selectAll(); 87 } 88 } 89 } 90