I would like to know how I can in a QTextEdit
allow only the entry of numbers, is there any property for it?
PS: I need you not to write or enter the QTextEdit
letters.
I would like to know how I can in a QTextEdit
allow only the entry of numbers, is there any property for it?
PS: I need you not to write or enter the QTextEdit
letters.
You can choose to inherit from QTextEdit and overwrite the event
method or you can install an event filter.
To make use of an event filter you need an object that inherits from QObject
... it can be the own window that contains the QTextArea
or a separate class, that's to your liking. What is really important is that the class in question implements the eventFilter
method. This method receives two arguments:
And the function must return true
or false
depending on whether you want to deactivate or not the event (it can be deactivated to cancel the event or simply because the event has already been treated and standard behavior is not desired).
Assuming that it is the window itself that implements the function, the system could look like this:
NOTE : This example assumes that the QTextArea
object is called textArea
.
MainWindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
bool eventFilter(QObject* object, QEvent* event) override;
private:
Ui::MainWindow *ui;
};
mainWindow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Instalamos el filtro de eventos
ui->textEdit->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject* object, QEvent* event)
{
if( ui->textEdit == object )
{
if ( event->type() == QEvent::KeyPress )
{
auto keyPress = static_cast<QKeyEvent*>(event);
switch( keyPress->key() )
{
// numeros
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:
// tecla de borrar (backspace)
case Qt::Key_Back:
// tecla suprimir
case Qt::Key_Delete:
// cursor
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Up:
case Qt::Key_Down:
break; // A estas teclas se les da el tratamiento por defecto
default:
return true; // se desactivan todas las demás
}
}
}
return false;
}
And that's it, you do not have to be born anything else. If you try the example you will see that the control will only support numeric digits.