Search code examples
qtuser-interfaceinput

QErrorMessage and QValidator


I'm trying to use some of the widgets provided in Qt to control my user input. I want the error message to display exactly what's wrong with the user input so I thought that using a switch statement would be best.

My main project will get a lot of user input and it feels like there should be an easier way. The Qt documentation lead me to believe that QValidator is at heart an enumerator data type. So I though I could use it in the switch statement however it doesn't seem to come up as an int.

I'm not sure how to bring in an int value to make this work without defeating the intended convenience of the QValidator.

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QValidator>
#include <QErrorMessage>
#include <QString>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButtonValidate, SIGNAL(clicked()), this, SLOT(checkData()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::checkData()
{
    QValidator *doubleValidator = new QDoubleValidator();
    switch(ui->lineEditValidate->setValidator(doubleValidator))
    {
    case 0:
        QErrorMessage *error0 = new QErrorMessage(this);
        error0->showMessage("The input is invalid");
        break;
    case 1:
        QErrorMessage *error1 = new QErrorMessage(this);
        error1->showMessage("The input is incomplete");
        break;
    case 2:
        break;
    default:
        QErrorMessage *error = new QErrorMessage(this);
        error->showMessage("No input");
    }
}

Solution

  • In this line of code

    switch(ui->lineEditValidate->setValidator(doubleValidator))
    

    you're attempting to switch on the return value of the setValidator() function call, which returns void.

    From what I gather, it looks like you want to do something along these lines:

    In the constructor:

    ui->setupUi(this);
    connect(ui->pushButtonValidate, SIGNAL(clicked()), this, SLOT(checkData()));
    QValidator *doubleValidator = new QDoubleValidator();
    ui->lineEditValidate->setValidator(doubleValidator);
    

    and in checkData()

    int pos = 0;
    switch(ui->lineEditValidate->validator()->validate(ui->lineEditValidate->text(), pos))
    {
    case QValidator::Invalid:
    ...
    case QValidator::Incomplete:
    ...
    case QValidator::Invalid:
    ...
    }