In these next few examples let’s look at some of the properties for a QLineEdit. This example will show how to add a mask to the edit widget to restrict the formatting.
#include <QtCore>
#include <QtGui>
class MainWindow : public QWidget
{
public:
MainWindow();
};
The declaration for MainWindow is the same as for example 5.
MainWindow::MainWindow()
{
setMinimumSize(700, 350);
// text edit
QLabel *label_1 = new QLabel("<h3>IPv4 (Mask)</h3>");
QLineEdit *text_1 = new QLineEdit();
text_1->setText("127.0.0.1");
text_1->setMinimumSize(400, 35);
text_1->setInputMask("000.000.000.000;_");
//
QLabel *label_2 = new QLabel("<h3>US/Canada Phone #</h3>");
QLineEdit *text_2 = new QLineEdit();
text_2->setText("(650) 555-1212");
text_2->setMinimumSize(400, 35);
text_2->setInputMask("(999) 999-9999");
//
QLabel *label_3 = new QLabel("<h3>License Key</h3>");
QLineEdit *text_3 = new QLineEdit();
text_3->setText("5555544444333332222211111");
text_3->setMinimumSize(400, 35);
text_3->setInputMask(">NNNNN-NNNNN-NNNNN-NNNNN-NNNNN;#");
QPushButton *pb_1 = new QPushButton();
pb_1->setText("Close");
QVBoxLayout *layout1 = new QVBoxLayout();
layout1->addSpacing(75);
layout1->addWidget(label_1);
layout1->addWidget(text_1);
layout1->addSpacing(35);
layout1->addWidget(label_2);
layout1->addWidget(text_2);
layout1->addSpacing(35);
layout1->addWidget(label_3);
layout1->addWidget(text_3);
layout1->addSpacing(75);
QHBoxLayout *layout2 = new QHBoxLayout();
layout2->addStretch();
layout2->addWidget(pb_1);
layout2->addStretch();
QVBoxLayout *layoutMain = new QVBoxLayout(this);
layoutMain->addLayout(layout1);
layoutMain->addSpacing(75);
layoutMain->addLayout(layout2);
connect(pb_1, &QPushButton::clicked,
this, &QWidget::close);
}
On lines 11, 19, and 27 we are calling the QLineEdit::setInputMask() method and passing a string. The contents of the string will determine what mask is applied to the text, which is entered by the user. For example, on line 19 the mask string is defined to enforce the formatting of a US or Canadian phone number.
For a table detailing what characters can be used for the mask, refer to QLineEdit::inputMask.
Main Function
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow *window = new MainWindow();
window->show();
return app.exec();
}
The source code for main() is the same as shown in example 3.
Running the Example
To build and run this example use the same CMake build file and commands as we showed for the first example. The only suggested modification is on line 2 of the CMakeLists.txt file, change “example_1” to “example_6”.